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 c80765e312..5ac12d5bb4 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -3,6 +3,3125 @@ twilio-python Changelog Here you can see the full list of changes between each twilio-python release. +[2026-05-07] Version 9.10.9 +--------------------------- +**Conversations** +- update actions api visibility + +**Memory** +- ## 2026-05-07 +- **Content updates**: +- include store api + + +[2026-05-07] Version 9.10.7 +--------------------------- +**Library - Chore** +- [PR #922](https://github.com/twilio/twilio-python/pull/922): add init for knowledge. Thanks to [@kridai](https://github.com/kridai)! + +[2026-05-06] Version 9.10.6 +--------------------------- +**Library - Chore** +- [PR #921](https://github.com/twilio/twilio-python/pull/921): new api updates. Thanks to [@kridai](https://github.com/kridai)! + +**Twiml** +- Set `recording_configuration_id` attribute to public visibility in ``, ``, `` verbs and `` noun + +**Api** +- Add RecordingConfigurationId parameter for CreateCall, CreateCallRecording, CreateConferenceRecording, and CreateParticipant endpoints + +**Authy** +- # Changelog +- ## v1 +- Added Authy API v1 under `/v1` — initial onboarding of Public API (`/v1/protected/*`), Device API (`/v1/json/*`), and Dashboard API (`/v1/dashboard/*`) behind REST Proxy using transparent proxy mode. + +**Data-ingress** +- ## 2026-04-21 +- **Content updates**: +- Updated description for `CreateDataSync` +- Updated description for `DeleteCloudAppDataset` +- Updated description for `DeleteWarehouseDataset` +- ## 2026-04-20 +- Minor updates (formatting, metadata) +- ## 2026-04-17 +- updated operationId for dataplane APIs,Minor updates (formatting, metadata) +- ## 2026-04-15 +- libraryVisibility to private +- ## 2026-04-14 +- **Added 1 new path(s)**: +- `/v1/DataSyncs/Latest` (GetLatestDataSyncs) + +**Memory** +- ## 2026-04-21 +- **Content updates**: +- Remove Prefer/Async-Operation headers +- ## 2026-04-21 +- **Content updates**: +- Added 301 response for `ListIdentifiers` and `GetIdentifier` +- Added 308 response for `DeleteProfile`, `CreateIdentifier`, `PatchIdentifier`, and `DeleteIdentifier` +- ## 2026-04-14 +- **Modified 1 path(s)**: +- `/v1/ControlPlane/Stores/{storeId}` (added delete) +- Minor updates (formatting, metadata) + +**Voice** +- ## 2026-04-17 +- Added `I-Twilio-Auth-Account` to `downstreamRequest` headers in POST /v3/Transcriptions transactions to document RestProxy account header injection +- ## 2026-04-10 +- Added initial version of Transcriptions V3 API +- Added POST /v3/Transcriptions endpoint to create a new transcription from a source ID or media URL + + +[2026-04-14] Version 9.10.5 +--------------------------- +**Twiml** +- Add `backgroundNoiseReduction`, `speechTimeout`, `deepgramSmartFormat`, `ignoreBackchannel`, `events` attributes to `` + +**Api** +- Enabled incoming phone numbers(IPN) public apis in stage-ie1 + +**Data-ingress** +- ## 2026-04-09 +- **Content updates**: +- Added parameter(s) to `GetDataSync`: datasetId +- ## 2026-04-09 +- Minor updates (formatting, metadata) +- ## 2026-04-06 +- Minor updates (formatting, metadata) +- ## 2026-04-06 +- Minor updates (formatting, metadata) +- ## 2026-04-06 +- Minor updates (formatting, metadata) +- ## 2026-04-06 +- Minor updates (formatting, metadata) +- ## 2026-04-06 +- **Content updates**: +- Added properties to `CloudAppSourceUpdate`: config +- Added properties to `CloudAppDatasetUpdate`: schedule +- Added properties to `WarehouseSourceUpdate`: config +- Added properties to `WarehouseDatasetUpdate`: schedule +- ## 2026-04-06 +- **Content updates**: +- Updated description for `GetCloudAppPreviewResult` +- Updated description for `GetWarehousePreviewResult` +- Updated description for `GetDataSampleResult` +- ## 2026-03-27 +- Add schema oneOf back without discriminator +- ## 2026-03-26 +- Minor updates (formatting, metadata) +- ## 2026-03-26 +- Added prod-us1 to supportedRealms for all endpoints +- ## 2026-03-25 +- Minor updates (formatting, metadata) +- ## 2026-03-24 +- Minor updates (formatting, metadata) +- ## 2026-03-24 +- Minor updates (formatting, metadata) +- ## 2026-03-24 +- Minor updates (formatting, metadata) +- ## 2026-03-24 +- **Added 10 new path(s)**: +- `/v1/DataSyncs` (ListDataSyncs, TriggerDataSync) +- `/v1/DataSyncs/{SyncId}` (GetDataSync) +- `/v1/CloudAppSources/{SourceId}/Objects` (ListCloudAppObjects) +- `/v1/CloudAppSources/{SourceId}/Objects/{Name}/Properties` (ListCloudAppObjectProperties) +- `/v1/CloudAppSources/{SourceId}/Objects/{Name}/Preview` (PreviewCloudAppObjectData) +- `/v1/CloudAppSources/{SourceId}/Objects/{Name}/Preview/{OperationId}` (GetCloudAppPreviewResult) +- `/v1/WarehouseSources/{SourceId}/Preview` (PreviewWarehouseData) +- `/v1/WarehouseSources/{SourceId}/Preview/{OperationId}` (GetWarehousePreviewResult) +- `/v1/DataSample` (TriggerDataSample) +- `/v1/DataSample/{OperationId}` (GetDataSampleResult) +- ## 2026-03-24 +- Minor updates (formatting, metadata) +- ## 2026-03-24 +- Use `explode: true` for query params when getting by ids and limit max items to 25 +- Make schema description for `Schema` more specific by using oneOf without discriminator for now. + +**Insights** +- Added Insights Domains endpoints under `/v3/InsightsDomains/*` (Query + Metadata) to provide a versioned, GA-ready namespace alongside existing `/preview` endpoints. + +**Mcp** +- # API Changes +- ## 2026-04-07 +- **Added 1 new path(s)**: +- `/v1/docs` (InvokeDocsMcp) + +**Memory** +- ## 2026-04-09 +- **Removed 2 path(s)**: +- `/v1/Stores/{storeId}/Profiles/Import` (ListProfileImports, CreateProfilesImport) +- `/v1/Stores/{storeId}/Profiles/Import/{importId}` (FetchProfileImport) +- libraryVisibility: private, docsVisibility: private +- ## 2026-04-08 +- **Content updates**: +- Added 301 response for `GetProfile` and `GetProfileTraits` +- Added canonical ID header to response for `GetProfile` and `GetProfileTraits` +- Add 308 response for `PatchProfile` +- ## 2026-04-07 +- Added `AGENT` and `UNKNOWN` values to `ParticipantType` enum +- ## 2026-04-06 +- **Content updates**: +- Added async operation support to `UpdateTraitGroup` 202 response (Operation-Id, Location, Retry-After headers; statusUrl in body) +- Added async operation support to `CreateDataMapping`, `UpdateDataMapping`, `DeleteDataMapping` 202 responses (Operation-Id, Location, Retry-After headers; statusUrl in body) +- ## 2026-03-30 +- **Content updates**: +- Updated description for `FetchProfileMemory` +- ## 2026-03-27 +- **Content updates**: +- Updated schema description for `TraitGroupCore` +- ## 2026-03-25 +- **Content updates**: +- Removed properties from `TraitDefinition`: displayName +- ## 2026-03-25 +- **Content updates**: +- Updated description for `UpdateProfileTraits` +- Updated description for `FetchIdentityResolutionSettings` +- Updated description for `UpdateIdentityResolutionSettings` +- Updated schema description for `IdentityResolutionSettingsCore` +- Updated schema description for `TraitGroupCore` +- Made all fields besides `idType` optional w/ defaults for schema `IdentifierConfig` +- ## 2026-03-24 +- **Content updates**: +- Added properties to `OperationStatus`: result + + +[2026-03-24] Version 9.10.4 +--------------------------- +**Data-ingress** +- # API Changes +- ## 2026-03-23 +- Added stage-us1 to supportedRealms for all endpoints +- ## 2026-03-20 +- **Content updates**: +- Removed estimatedCompletionTime from `LongRunningOperationResponse` +- Moved operationId from `LongRunningOperationResponse` to headers +- ## 2026-03-18 +- **Added 1 new path(s)**: +- `/v1/ControlPlane/Operations/{OperationId}` (GetControlPlaneOperationStatus) +- ## 2026-03-11 +- Minor updates (formatting, metadata) +- ## 2026-03-11 +- Minor updates (formatting, metadata) +- ## 2026-03-11 +- Minor updates (formatting, metadata) +- ## 2026-03-11 +- Minor updates (formatting, metadata) +- ## 2026-03-11 +- Minor updates (formatting, metadata) +- ## 2026-03-05 +- Initial release with 10 paths and 22 operations + +**Memory** +- ## 2026-03-19 +- **Added 1 new path(s)**: +- `/v1/ControlPlane/Operations/{operationId}` (FetchOperation) +- ## 2026-03-11 +- Minor updates (formatting, metadata) + + +[2026-03-10] Version 9.10.3 +--------------------------- +**Twiml** +- Rename `recording_configuration` to `recording_configuration_id` attribute in ``, ``, `` verbs and `` noun + +**Ace** +- # ACE Signals API Changes +- ## 2026-02-18 +- Initial release: POST /signals, GET/POST /signals/{signal_id}/results, GET /health +- Enables OneAdmin integration for synchronous signal ingestion and policy result polling +- Supports permission-based authorization for signal operations +- Health endpoint available for monitoring without authentication + +**Api** +- Added optional parameter `Confirmation` to Payments create endpoint to enable payment confirmation prompt before gateway submission +- Added optional parameter `RequireMatchingInputs` to Payments create endpoint for input confirmation in agent-assisted payment flows +- Added matcher capture types (`payment-card-number-matcher`, `expiration-date-matcher`, `security-code-matcher`, `postal-code-matcher`) to Payments update endpoint + +**Memory** +- ## 2026-03-06 +- **Modified 1 path(s)**: +- `/v1/Stores/{storeId}/Profiles/{profileId}/ConversationSummaries/{summaryId}` (added patch, get) + + +[2026-02-18] Version 9.10.2 +--------------------------- +**Api** +- Remove inequality examples from Calls StartTime and EndTime filter descriptions + +**Memory** +- ## 2026-02-06 +- Minor updates (formatting, metadata) +- ## 2026-02-06 +- Minor updates (formatting, metadata) +- ## 2026-02-06 +- ## 2026-01-23 +- ## 2026-01-23 +- **Added 3 new path(s)**: +- `/v1/Stores/{storeId}/Profiles/Imports` (ListProfileImportsV2, CreateProfilesImportV2) +- `/v1/Stores/{storeId}/Profiles/Imports/{importId}` (FetchProfileImportV2) +- **Removed 6 path(s)**: +- `/v1/KnowledgeBases/{kbId}/Knowledge` (ListKnowledge, CreateKnowledge) +- `/v1/KnowledgeBases/{kbId}/Search` (KnowledgeSearch) +- `/v1/KnowledgeBases/{kbId}/Knowledge/{knowledgeId}` (RetrieveKnowledge, PatchKnowledge, DeleteKnowledge) +- `/v1/KnowledgeBases/{kbId}/Knowledge/{knowledgeId}/Chunks` (ListKnowledgeChunks) +- `/v1/ControlPlane/KnowledgeBases` (ListKnowledgeBases, CreateKnowledgeBase) +- `/v1/ControlPlane/KnowledgeBases/{kbId}` (GetKnowledgeBase, UpdateKnowledgeBase, DeleteKnowledgeBase) +- ## 2026-01-05 +- ## 2026-01-05 +- Initial release with 26 paths and 48 operations + + +[2026-02-05] Version 9.10.1 +--------------------------- +**Library - Fix** +- [PR #907](https://github.com/twilio/twilio-python/pull/907): Regional API domain processing. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Twiml** +- Add `recording_configuration` attribute to `` noun + +**Api** +- Clarify the behavior of date filters with the Calls API +- Added Phone Number `type` property to `/IncomingPhoneNumbers` resource + +**Memory** +- ## 2026-01-23 +- No path changes (updated metadata only) +- ## 2026-01-22 +- No path changes (updated metadata only) +- ## 2026-01-22 +- **Modified 1 path(s)**: +- `/v1/Stores/{storeId}/Profiles/{profileId}` (added delete) + + +[2026-01-22] Version 9.10.0 +--------------------------- +**Library - Feature** +- [PR #896](https://github.com/twilio/twilio-python/pull/896): Token pagination support. Thanks to [@kridai](https://github.com/kridai)! +- [PR #902](https://github.com/twilio/twilio-python/pull/902): add support for response headers. Thanks to [@kridai](https://github.com/kridai)! + +**Library - Chore** +- [PR #904](https://github.com/twilio/twilio-python/pull/904): fix lint errors. Thanks to [@kridai](https://github.com/kridai)! +- [PR #901](https://github.com/twilio/twilio-python/pull/901): Error response changes. Thanks to [@kridai](https://github.com/kridai)! + +**Library - Fix** +- [PR #903](https://github.com/twilio/twilio-python/pull/903): allow nullable headers response field. Thanks to [@kridai](https://github.com/kridai)! + +**Twiml** +- Added support for and inside + +**Assistants** +- AI Assistants v1 release + +**Autopilot** +- Remove Export resource from Autopilot Assistant +- Add dialogue_sid param to Query list resource +- Add Restore resource to Autopilot Assistant +- Add one new property in Query i.e dialogue_sid +- Add Export resource to Autopilot Assistant. +- Adds two new properties in Assistant i.e needs_model_build and development_stage +- Add Webhooks resource to Autopilot Assistant. +- Introduce `autopilot` subdomain with all resources from `preview.understand` + +**Compliance** +- Added the new InventoryComplianceInsights API under version `/v1`. + +**Content** +- changes for adding v2 endpoints + +**Marketplace** +- Initial transition to Marketplace domain + +**Memory** +- # API Changes +- ## 2026-01-15 +- No path changes (updated metadata only) +- ## 2026-01-13 +- **Added 1 new path(s)**: +- `/v1/Stores/{storeId}/Profiles/{profileId}/ConversationSummaries/{summaryId}` (DeleteProfileConversationSummary) +- ## 2026-01-12 +- No path changes (updated metadata only) +- ## 2026-01-12 +- No path changes (updated metadata only) +- ## 2026-01-12 +- No path changes (updated metadata only) +- ## 2026-01-12 +- **Added 2 new path(s)**: +- `/v1/Stores/{storeId}/Profiles/Imports` (ListProfileImportsV2, ImportProfilesV2) +- `/v1/Stores/{storeId}/Profiles/Imports/{importId}` (GetProfileImportV2) +- ## 2026-01-13 +- No path changes (updated metadata only) +- ## 2026-01-07 +- No path changes (updated metadata only) +- ## 2026-01-05 +- No path changes (updated metadata only) +- ## 2025-12-17 +- No path changes (updated metadata only) +- ## 2025-12-17 +- No path changes (updated metadata only) +- ## 2025-12-17 +- **Added 1 new path(s)**: +- `/v1/Stores/{storeId}/Profiles/{profileId}/Observations/{observationId}/Revisions` (ListObservationRevisions) + +**Sender-ids** +- Added all v2 sender-id-service endpoints + +**Trusthub** +- Add new delete endpoint for compliance_registration. + +**Voice** +- Add ProvisioningStatus public API endpoints. + +**Wise_owl** +- Init API as open-api spec +- Updated Get Chat, Send Message and Create Chat to include `contexts` in Message, instead of root Chat + +**Www** +- Port APIs from oauth.twilio.com to www.twilio.com + + +[2026-01-07] Version 9.9.1 +-------------------------- +**Api** +- Added optional parameter `clientNotificationUrl` for create call api +- Added optional parameter `clientNotificationUrl` for create participant api + + +[2025-12-17] Version 9.9.0 +-------------------------- +**Library - Fix** +- [PR #898](https://github.com/twilio/twilio-python/pull/898): allow 2XX response for delete operation. Thanks to [@kridai](https://github.com/kridai)! + +**Trunking** +- Corrected the type used for phone number capabilities when accessed through a Trunk. **(breaking change)** +- Corrected the type used for phone number capabilities when accessed through a Trunk. **(breaking change)** + +**Trusthub** +- Added new parameters in in toll-free initialize api payload. +- Remove the invalid status transition to Draft from the examples +- Change the value of email to a valid one in the examples. + + +[2025-12-03] Version 9.8.8 +-------------------------- +**Library - Fix** +- [PR #895](https://github.com/twilio/twilio-python/pull/895): Regional API domain processing. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Api** +- Add `twiml_session` resource for calls +- Add `twiml_session` resource for calls + +**Monitor** +- Update default output properties + +**Trusthub** +- Added customer_profile_sid in toll-free initialize api payload. + + +[2025-11-20] Version 9.8.7 +-------------------------- +**Memory** +- # Memory API Changes +- Added initial Memory API endpoints with darkseagreen badge status + + +[2025-11-11] Version 9.8.6 +-------------------------- +**Twiml** +- Add new noun `` +- Add support for `` noun under `` verb + + +[2025-10-28] Version 9.8.5 +-------------------------- +**Ai** +- Add `error` as possible transcript status +- Add `error` as possible transcript status + +**Chat** +- Updated v2 UserChannel `channel_status` from `not_participating` to `notParticipating` + +**Intelligence** +- Make intelligence work with RestProxy +- Add additional enums to better represent the possible states +- Add `error` enum to transcription status to better align with possible outputs +- Add `json` output type to text classification + +**Trusthub** +- Remove required parameter Primary Profile Sid from compliance_inquiry and compliance_inquiry_individual + +**Accounts** +- Add Messaging GeoPermissions API changes + + +[2025-10-14] Version 9.8.4 +-------------------------- +**Library - Chore** +- [PR #887](https://github.com/twilio/twilio-python/pull/887): remove auth from request.__str__(). Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Library - Docs** +- [PR #886](https://github.com/twilio/twilio-python/pull/886): update oauth example. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Api** +- Updated description for property `CallerDisplayName` for participant create request +- Updated description for property `CallerDisplayName` for participant create request + +**Accounts** +- FILE_IS_AUTO_GENERATED: false + + +[2025-09-30] Version 9.8.3 +-------------------------- +**Library - Chore** +- [PR #882](https://github.com/twilio/twilio-python/pull/882): change oauth token endpoint. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Insights** +- Replace `field` with `key` in Request Filters and Response Metadata Filters and for Reports API + + +[2025-09-25] Version 9.8.2 +-------------------------- +**Api** +- Added optional parameter `CallerDisplayName` for conference participant outbound +- Updated description for property `to` in the participant create request + + +[2025-09-18] Version 9.8.1 +-------------------------- +**Api** +- Add `date_created` property to media resource and date_created filtering parameters for read action +- Updated the Recordings Resource `channels` property to clarify channels = # of channels in the recording resource and how to specify the # of channels in recording download + +**Intelligence** +- Add encryption_credential_sid field in transcripts and services in v2 + +**Trusthub** +- Remove beta feature flag for all TH APIs +- Remove beta feature flag for ComplianceInquiries API to support OneConsole traffic + +**Twiml** +- Add new noun `` + + +[2025-09-04] Version 9.8.0 +-------------------------- +**Api** +- Remove usage category enum from usage record and usage triggers API **(breaking change)** + + +[2025-08-28] Version 9.7.2 +-------------------------- +**Studio** +- Add `type` to Step resource APIs + +**Verify** +- Allow to update all passkeys parameters in the service update + + +[2025-08-18] Version 9.7.1 +-------------------------- +**Accounts** +- Update beta feature flag for consent and contact bulk upsert APIs + +**Api** +- Add multiple missing usage categories to usage records and usage triggers api +- Add `channels-whatsapp-template-marketing` and `channels-whatsapp-template-utility` to usage categories + +**Conversations** +- Fix `state` spelling for `initializing` enum value +- Update `state` to include `intializing` for ServiceConversationWithParticipants and ConversationWithParticipants + +**Flex** +- Adding new optional parameter `identity` to `web_channels` API in version `v2` + +**Trusthub** +- Add required Permissions to the ComplianceInquiries API + +**Verify** +- Add passkeys support to Verify API creating and updating services. +- Update `ienum` type for Factor creation +- Add passkeys as challenge and factor type + + +[2025-07-24] Version 9.7.0 +-------------------------- +**Library - Fix** +- [PR #878](https://github.com/twilio/twilio-python/pull/878): Remove not existence class ServiceList. Thanks to [@lopenchi](https://github.com/lopenchi)! + +**Events** +- Remove `SinkSid` parameter when updating subscriptions. **(breaking change)** + +**Twiml** +- Remove Duplicates. +- Add Polly Generative voices. +- Add Latest Google (Chirp3-HD) voices. + + +[2025-07-10] Version 9.6.5 +-------------------------- +**Library - Fix** +- [PR #874](https://github.com/twilio/twilio-python/pull/874): delete non existing import in rest/preview. Thanks to [@lopenchi](https://github.com/lopenchi)! + +**Flex** +- update team name for web_channel, webchat_init_token, webchat_refresh_token + + +[2025-07-03] Version 9.6.4 +-------------------------- +**Library - Chore** +- [PR #865](https://github.com/twilio/twilio-python/pull/865): Remove references to microvisor. Thanks to [@akhani18](https://github.com/akhani18)! +- [PR #872](https://github.com/twilio/twilio-python/pull/872): support Python 3.13. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #870](https://github.com/twilio/twilio-python/pull/870): remove knowledge domain. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Bulkexports** +- Changed the type of 'details' field to be a list of objects instead of a single object + +**Conversations** +- Updates to `method` casing for ConfgurationAddress, ConversationScopedWebhook, and ServiceConversationScopedWebhook for RestProxy compatibility + +**Proxy** +- remove shortcodes resource as its no longer used + +**Serverless** +- Change log field level from type `ienum` to `string` in Logs api + +**Taskrouter** +- Remove `URL-encoded` from attributes param definition in tasks + +**Trunking** +- Added `symmetric_rtp_enabled` property on Trunks. + +**Twiml** +- Add support for `` noun under `` verb + + +[2025-06-12] Version 9.6.3 +-------------------------- +**Library - Chore** +- [PR #869](https://github.com/twilio/twilio-python/pull/869): Remove knowledge files. Thanks to [@krishnakalluri](https://github.com/krishnakalluri)! + +**Api** +- Change DependentPhoneNumber `capabilities` type `object` and `date_created`, `date_updated` to `date_time` +- Updated the `Default` value from 0 to 1 in the Recordings Resource `channels` property + +**Serverless** +- Update `ienum` type level in Logs api + +**Verify** +- Update Channel list in Verify Attempst API +- Update `ienum` type for Conversion_Status in Verify Attempts API + +**Twiml** +- Add `us2` to the list of supported values for the region attribute in the `` TwiML noun. + + +[2025-05-29] Version 9.6.2 +-------------------------- +**Library - Chore** +- [PR #862](https://github.com/twilio/twilio-python/pull/862): update iam token endpoint. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Api** +- Added several usage category enums to `usage_record` API + +**Numbers** +- Update the porting documentation + +**Verify** +- Update `ienum` type for Channels in Verify Attempts API + + +[2025-05-13] Version 9.6.1 +-------------------------- +**Accounts** +- Changes to add date_of_consent param in Bulk Consent API + +**Api** +- Change `friendly_name`, `date_created` and `date_updated` properties to type `string`. + +**Twiml** +- Update twiml definition for `` and `` + + +[2025-05-05] Version 9.6.0 +-------------------------- +**Library - Fix** +- [PR #848](https://github.com/twilio/twilio-python/pull/848): Timezone changes in token_auth_strategy.py. Thanks to [@Pablo2113](https://github.com/Pablo2113)! +- [PR #853](https://github.com/twilio/twilio-python/pull/853): Fix deprecated/invalid config in `setup.cfg`. Thanks to [@abravalheri](https://github.com/abravalheri)! + +**Library - Chore** +- [PR #858](https://github.com/twilio/twilio-python/pull/858): fix oauth examples. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Library - Docs** +- [PR #855](https://github.com/twilio/twilio-python/pull/855): update pagination usage in README.md. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Api** +- Add `response_key` for `Usage Triggers` fetch endpoint. + +**Flex** +- Add Update Interaction API +- Adding `webhook_ttid` as optional parameter in Interactions API + +**Serverless** +- Add node22 as a valid Build runtime +- Add node20 as a valid Build runtime + +**Video** +- removed `transcribe_participants_on_connect` and `transcriptions_configuration` from the room resource **(breaking change)** +- Added `transcribe_participants_on_connect` and `transcriptions_configuration` to the room resource + + +[2025-04-07] Version 9.5.2 +-------------------------- +**Studio** +- Add documentation for parent_step_sid field in Step resource + + +[2025-03-20] Version 9.5.1 +-------------------------- +**Accounts** +- Update Safelist API docs as part of prefix supoort + +**Flex** +- Removing `first_name`, `last_name`, and `friendly_name` from the Flex User API + +**Messaging** +- Add missing tests under transaction/phone_numbers and transaction/short_code + + +[2025-03-11] Version 9.5.0 +-------------------------- +**Library - Feature** +- [PR #850](https://github.com/twilio/twilio-python/pull/850): Update UPGRADE.md. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Library - Fix** +- [PR #847](https://github.com/twilio/twilio-python/pull/847): AssistantsBase import. Thanks to [@sbansla](https://github.com/sbansla)! + +**Api** +- Add the missing `emergency_enabled` field for `Address Service` endpoints + +**Messaging** +- Add missing enums for A2P and TF + +**Numbers** +- add missing enum values to hosted_number_order_status + +**Twiml** +- Convert Twiml Attribute `speechModel` of type enum to string **(breaking change)** + + +[2025-02-20] Version 9.4.6 +-------------------------- +**Library - Chore** +- [PR #842](https://github.com/twilio/twilio-python/pull/842): issue 841. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Flex** +- Adding Digital Transfers APIs under v1/Interactions + +**Numbers** +- Convert webhook_type to ienum type in v1/Porting/Configuration/Webhook/{webhook_type} + +**Trusthub** +- Changing TrustHub SupportingDocument status enum from lowercase to uppercase since kyc-orch returns status capitalized and rest proxy requires strict casing + + +[2025-02-11] Version 9.4.5 +-------------------------- +**Api** +- Change downstream url and change media type for file `base/api/v2010/validation_request.json`. + +**Intelligence** +- Add json_results for Generative JSON operator results + +**Messaging** +- Add DestinationAlphaSender API to support Country-Specific Alpha Senders + +**Video** +- Change codec type from enum to case-insensitive enum in recording and room_recording apis + + +[2025-01-28] Version 9.4.4 +-------------------------- +**Library - Fix** +- [PR #822](https://github.com/twilio/twilio-python/pull/822): Fix for 10 vulnerabilities. Thanks to [@twilio-product-security](https://github.com/twilio-product-security)! + +**Library - Chore** +- [PR #834](https://github.com/twilio/twilio-python/pull/834): update httpclient. Thanks to [@manisha1997](https://github.com/manisha1997)! +- [PR #837](https://github.com/twilio/twilio-python/pull/837): enable newer versions of aiohttp-retry. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #833](https://github.com/twilio/twilio-python/pull/833): created bug report issue template. Thanks to [@sbansla](https://github.com/sbansla)! + +**Api** +- Add open-api file tag to `conference/call recordings` and `recording_transcriptions`. + +**Events** +- Add support for subaccount subscriptions (beta) + +**Insights** +- add new region to conference APIs + +**Lookups** +- Add new `parnter_sub_id` query parameter to the lookup request + + +[2025-01-13] Version 9.4.3 +-------------------------- +**Messaging** +- Adds validity period Default value in service resource documentation + + +[2025-01-09] Version 9.4.2 +-------------------------- +**Library - Chore** +- [PR #832](https://github.com/twilio/twilio-python/pull/832): remove test for 3.7. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Numbers** +- Change beta feature flag to use v2/BulkHostedNumberOrders + + +[2024-12-13] Version 9.4.1 +-------------------------- +**Library - Fix** +- [PR #827](https://github.com/twilio/twilio-python/pull/827): Fixing init file for preview iam domain. Thanks to [@AsabuHere](https://github.com/AsabuHere)! + +**Library - Chore** +- [PR #826](https://github.com/twilio/twilio-python/pull/826): fix orgs api changes. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + + +[2024-12-12] Version 9.4.0 +-------------------------- +**Library - Feature** +- [PR #825](https://github.com/twilio/twilio-python/pull/825): Docs update and examples for organization api uptake and public oauth. Thanks to [@AsabuHere](https://github.com/AsabuHere)! +- [PR #815](https://github.com/twilio/twilio-python/pull/815): Organizations Api uptake for twilio-python. Thanks to [@AsabuHere](https://github.com/AsabuHere)! + + +[2024-12-05] Version 9.3.8 +-------------------------- +**Api** +- Add optional parameter `intelligence_service` to `transcription` +- Updated `phone_number_sid` to be populated for sip trunking terminating calls. + +**Numbers** +- Add Update Hosted Number Order V2 API endpoint +- Update Port in docs + +**Twiml** +- Add optional parameter `intelligence_service` to `` +- Add support for new `` and `` noun +- Add `events` attribute to `` verb + + +[2024-11-15] Version 9.3.7 +-------------------------- +**Library - Chore** +- [PR #819](https://github.com/twilio/twilio-python/pull/819): use older verison of aiohttp_retry. Thanks to [@sbansla](https://github.com/sbansla)! + +**Api** +- Added `ivr-virtual-agent-custom-voices` and `ivr-virtual-agent-genai` to `usage_record` API. +- Add open-api file tag to realtime_transcriptions + +**Taskrouter** +- Add `api-tag` property to workers reservation +- Add `api-tag` property to task reservation + + +[2024-10-25] Version 9.3.6 +-------------------------- +**Library - Chore** +- [PR #818](https://github.com/twilio/twilio-python/pull/818): removing unavailable references from init files. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + + +[2024-10-24] Version 9.3.5 +-------------------------- +**Conversations** +- Expose ConversationWithParticipants resource that allows creating a conversation with participants + + +[2024-10-17] Version 9.3.4 +-------------------------- +**Api** +- Add response key `country` to fetch AvailablePhoneNumber resource by specific country. + +**Messaging** +- Make library and doc public for requestManagedCert Endpoint + + +[2024-10-03] Version 9.3.3 +-------------------------- +**Library - Chore** +- [PR #816](https://github.com/twilio/twilio-python/pull/816): add assistants init files. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Messaging** +- Add A2P external campaign CnpMigration flag + +**Numbers** +- Add address sid to portability API + +**Verify** +- Add `SnaClientToken` optional parameter on Verification check. +- Add `EnableSnaClientToken` optional parameter for Verification creation. + + +[2024-09-25] Version 9.3.2 +-------------------------- +**Accounts** +- Update docs and mounts. +- Change library visibility to public +- Enable consent and contact bulk upsert APIs in prod. + +**Serverless** +- Add is_plugin parameter in deployments api to check if it is plugins deployment + + +[2024-09-18] Version 9.3.1 +-------------------------- +**Library - Chore** +- [PR #813](https://github.com/twilio/twilio-python/pull/813): add static init file to iam domain. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Intelligence** +- Remove public from operator_type +- Update operator_type to include general-availablity and deprecated + +**Numbers** +- Remove beta flag for bundle clone API + + +[2024-09-05] Version 9.3.0 +-------------------------- +**Iam** +- updated library_visibility public for new public apikeys + +**Numbers** +- Add new field in Error Codes for Regulatory Compliance. +- Change typing of Port In Request date_created field to date_time instead of date **(breaking change)** + + +[2024-08-26] Version 9.2.4 +-------------------------- +**Library - Chore** +- [PR #810](https://github.com/twilio/twilio-python/pull/810): add license identifier to project metadata. Thanks to [@mschoettle](https://github.com/mschoettle)! +- [PR #808](https://github.com/twilio/twilio-python/pull/808): preview iam removal. Thanks to [@manisha1997](https://github.com/manisha1997)! +- [PR #807](https://github.com/twilio/twilio-python/pull/807): update intersphinx_mapping. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #804](https://github.com/twilio/twilio-python/pull/804): add init file. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Api** +- Update documentation of `error_code` and `error_message` on the Message resource. +- Remove generic parameters from `transcription` resource +- Added public documentation for Payload Data retrieval API + +**Flex** +- Adding update Flex User api + +**Insights** +- Added 'branded', 'business_profile' and 'voice_integrity' fields in List Call Summary + +**Intelligence** +- Add `words` array information to the Sentences v2 entity. +- Add `X-Rate-Limit-Limit`, `X-Rate-Limit-Remaining`, and `X-Rate-Limit-Config` headers for Operator Results. +- Change the path parameter when fetching an `/OperatorType/{}` from `sid` to `string` to support searching by SID or by name +- Add `X-Rate-Limit-Limit`, `X-Rate-Limit-Remaining`, and `X-Rate-Limit-Config` headers for Transcript and Service endpoints. + +**Messaging** +- Adds two new channel senders api to add/remove channel senders to/from a messaging service +- Extend ERC api to accept an optional attribute in request body to indicate CNP migration for an ERC + +**Numbers** +- Modify visibility to public in bundle clone API +- Add `port_date` field to Port In Request and Port In Phone Numbers Fetch APIs +- Change properties docs for port in phone numbers api +- Add is_test body param to the Bundle Create API +- Change properties docs for port in api + +**Trusthub** +- Add new field in themeSetId in compliance_inquiry. + +**Verify** +- Update `custom_code_enabled` description on verification docs + + +[2024-07-02] Version 9.2.3 +-------------------------- +**Intelligence** +- Deprecate account flag api.twilio-intelligence.v2 + + +[2024-06-27] Version 9.2.2 +-------------------------- +**Api** +- Add `transcription` resource + +**Flex** +- Changed mount name for flex_team v2 api + +**Intelligence** +- Add `X-Rate-Limit-Limit`, `X-Rate-Limit-Remaining`, and `X-Rate-Limit-Config` as Response Headers to Operator resources + +**Numbers** +- Added include_constraints query parameter to the Regulations API + +**Twiml** +- Add support for `` noun + + +[2024-06-21] Version 9.2.1 +-------------------------- +**Api** +- Add beta feature request managed cert + + +[2024-06-18] Version 9.2.0 +-------------------------- +**Library - Chore** +- [PR #796](https://github.com/twilio/twilio-python/pull/796): adding contentType in post and put. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Events** +- Add `status` and `documentation_url` to Event Types + +**Lookups** +- Removed unused `fraud` lookups in V1 only to facilitate rest proxy migration + +**Numbers** +- Add date_created field to the Get Port In Request API +- Rename the `status_last_time_updated_timestamp` field to `last_updated` in the Get Port In Phone Number API **(breaking change)** +- Add Rejection reason and rejection reason code to the Get Port In Phone Number API +- Remove the carrier information from the Portability API + +**Proxy** +- Change property `type` from enum to ienum + +**Trusthub** +- Add skipMessagingUseCase field in compliance_tollfree_inquiry. + + +[2024-06-06] Version 9.1.1 +-------------------------- +**Api** +- Mark MaxPrice as obsolete + +**Lookups** +- Update examples for `phone_number_quality_score` + +**Messaging** +- List tollfree verifications on parent account and all sub-accounts + + +[2024-05-24] Version 9.1.0 +-------------------------- +**Library - Chore** +- [PR #789](https://github.com/twilio/twilio-python/pull/789): [Snyk] Security upgrade aiohttp from 3.8.6 to 3.9.4. Thanks to [@twilio-product-security](https://github.com/twilio-product-security)! + +**Library - Fix** +- [PR #716](https://github.com/twilio/twilio-python/pull/716): Connection pool is full, discarding connection. Thanks to [@lightiverson](https://github.com/lightiverson)! + +**Api** +- Add ie1 as supported region for UserDefinedMessage and UserDefinedMessageSubscription. + +**Flex** +- Adding validated field to `plugin_versions` +- Corrected the data type for `runtime_domain`, `call_recording_webhook_url`, `crm_callback_url`, `crm_fallback_url`, `flex_url` in Flex Configuration +- Making `routing` optional in Create Interactions endpoint + +**Intelligence** +- Expose operator authoring apis to public visibility +- Deleted `language_code` parameter from updating service in v2 **(breaking change)** +- Add read_only_attached_operator_sids to v2 services + +**Numbers** +- Add API endpoint for GET Porting Webhook Configurations By Account SID +- Remove bulk portability api under version `/v1`. **(breaking change)** +- Removed porting_port_in_fetch.json files and move the content into porting_port_in.json files +- Add API endpoint to deleting Webhook Configurations +- Add Get Phone Number by Port in request SID and Phone Number SID api +- Add Create Porting webhook configuration API +- Added bundle_sid and losing_carrier_information fields to Create PortInRequest api to support Japan porting + +**Taskrouter** +- Add back `routing_target` property to tasks +- Add back `ignore_capacity` property to tasks +- Removing `routing_target` property to tasks due to revert +- Removing `ignore_capacity` property to tasks due to revert +- Add `routing_target` property to tasks +- Add `ignore_capacity` property to tasks + +**Trusthub** +- Add new field errors to bundle as part of public API response in customer_profile.json and trust_product.json **(breaking change)** +- Add themeSetId field in compliance_tollfree_inquiry. + +**Verify** +- Update `friendly_name` description on service docs + + +[2024-04-18] Version 9.0.5 +-------------------------- +**Library - Chore** +- [PR #742](https://github.com/twilio/twilio-python/pull/742): [Snyk] Fix for 3 vulnerabilities. Thanks to [@twilio-product-security](https://github.com/twilio-product-security)! + +**Flex** +- Add header `ui_version` to `web_channels` API + +**Messaging** +- Redeploy after failed pipeline + +**Numbers** +- Add Delete Port In request phone number api and Add Delete Port In request api + + +[2024-04-04] Version 9.0.4 +-------------------------- +**Api** +- Correct conference filtering by date_created and date_updated documentation, clarifying that times are UTC. + +**Flex** +- Remove optional parameter from `plugins` and it to `plugin_versions` + +**Lookups** +- Add new `pre_fill` package to the lookup response + +**Messaging** +- Cleanup api.messaging.next-gen from Messaging Services endpoints +- Readd Sending-Window after fixing test failure + +**Verify** +- Add `whatsapp.msg_service_sid` and `whatsapp.from` parameters to create, update, get and list of services endpoints + +**Voice** +- Correct conference filtering by date_created and date_updated documentation, clarifying that times are UTC. + +**Twiml** +- Add new `token_type` value `payment-method` for `Pay` verb + + +[2024-04-01] Version 9.0.3 +-------------------------- +**Api** +- Add property `queue_time` to conference participant resource +- Update RiskCheck documentation +- Correct call filtering by start and end time documentation, clarifying that times are UTC. + +**Flex** +- Adding optional parameter to `plugins` + +**Media** +- Remove API: MediaProcessor + +**Messaging** +- Remove Sending-Window due to test failure +- Add Sending-Window as a response property to Messaging Services, gated by a beta feature flag + +**Numbers** +- Correct valid_until_date field to be visible in Bundles resource +- Adding port_in_status field to the Port In resource and phone_number_status and sid fields to the Port In Phone Number resource + +**Oauth** +- Modified token endpoint response +- Added refresh_token and scope as optional parameter to token endpoint + +**Trusthub** +- Add update inquiry endpoint in compliance_registration. +- Add new field in themeSetId in compliance_registration. + +**Voice** +- Correct call filtering by start and end time documentation, clarifying that times are UTC. + +**Twiml** +- Add support for new Google voices (Q1 2024) for `Say` verb - gu-IN voices +- Add support for new Amazon Polly and Google voices (Q1 2024) for `Say` verb - Niamh (en-IE) and Sofie (da-DK) voices + + +[2024-03-15] Version 9.0.2 +-------------------------- +**Oauth** +- Add new APIs for vendor authorize and token endpoints + + +[2024-03-12] Version 9.0.1 +-------------------------- +**Library - Chore** +- [PR #775](https://github.com/twilio/twilio-python/pull/775): removing preview.understand references. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Api** +- Correct precedence documentation for application_sid vs status_callback in message creation +- Mark MaxPrice as deprecated + +**Flex** +- Making `plugins` visibility to public + +**Messaging** +- Add new `errors` attribute to the Brand Registration resource. +- Mark `brand_feedback` attribute as deprecated. +- Mark `failure_reason` attribute as deprecated. +- The new `errors` attribute is expected to provide additional information about Brand registration failures and feedback (if any has been provided by The Campaign Registry). Consumers should use this attribute instead of `brand_feedback` and `failure_reason`. + +**Numbers** +- Correcting mount_name for porting port in fetch API + +**Trusthub** +- Add new field in statusCallbackUrl in compliance_registration. +- Add new field in isvRegisteringForSelfOrTenant in compliance_registration. + +**Twiml** +- Expanded description of Action parameter for Message verb + + +[2024-02-27] Version 9.0.0 +-------------------------- +**Note:** This release contains breaking changes, check our [upgrade guide](./UPGRADE.md###-2024-02-20-8xx-to-9xx) for detailed migration notes. + +**Library - Feature** +- [PR #767](https://github.com/twilio/twilio-python/pull/767): Merge branch '9.0.0-rc' into main. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! **(breaking change)** + +**Library - Chore** +- [PR #771](https://github.com/twilio/twilio-python/pull/771): added check for unset values. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #768](https://github.com/twilio/twilio-python/pull/768): cluster tests enabled. Thanks to [@sbansla](https://github.com/sbansla)! + +**Api** +- remove feedback and feedback summary from call resource + +**Flex** +- Adding `routing_properties` to Interactions Channels Participant + +**Lookups** +- Add new `line_status` package to the lookup response +- Remove `live_activity` package from the lookup response **(breaking change)** + +**Messaging** +- Add tollfree multiple rejection reasons response array + +**Trusthub** +- Add ENUM for businessRegistrationAuthority in compliance_registration. **(breaking change)** +- Add new field in isIsvEmbed in compliance_registration. +- Add additional optional fields in compliance_registration for Individual business type. + +**Twiml** +- Add support for new Amazon Polly and Google voices (Q1 2024) for `Say` verb + + +[2024-02-09] Version 8.13.0 +--------------------------- +**Library - Fix** +- [PR #753](https://github.com/twilio/twilio-python/pull/753): added boolean_to_string converter. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Library - Chore** +- [PR #758](https://github.com/twilio/twilio-python/pull/758): disable cluster test. Thanks to [@sbansla](https://github.com/sbansla)! +- [PR #760](https://github.com/twilio/twilio-python/pull/760): run make prettier. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Api** +- Updated service base url for connect apps and authorized connect apps APIs **(breaking change)** +- Update documentation to reflect RiskCheck GA +- Added optional parameter `CallToken` for create participant api + +**Events** +- Marked as GA + +**Flex** +- Adding `flex_instance_sid` to Flex Configuration +- Adding `provisioning_status` for Email Manager +- Adding `offline_config` to Flex Configuration + +**Insights** +- add flag to restrict access to unapid customers +- decommission voice-qualitystats-endpoint role + +**Intelligence** +- Add text-generation operator (for example conversation summary) results to existing OperatorResults collection. + +**Lookups** +- Remove `carrier` field from `sms_pumping_risk` and leave `carrier_risk_category` **(breaking change)** +- Remove carrier information from call forwarding package **(breaking change)** + +**Messaging** +- Add update instance endpoints to us_app_to_person api +- Add tollfree edit_allowed and edit_reason fields +- Update Phone Number, Short Code, Alpha Sender, US A2P and Channel Sender documentation +- Add DELETE support to Tollfree Verification resource + +**Numbers** +- Add Get Port In request api + +**Push** +- Migrated to new Push API V4 with Resilient Notification Delivery. + +**Serverless** +- Add node18 as a valid Build runtime + +**Taskrouter** +- Add `jitter_buffer_size` param in update reservation +- Add container attribute to task_queue_bulk_real_time_statistics endpoint +- Remove beta_feature check on task_queue_bulk_real_time_statistics endpoint + +**Trusthub** +- Add optional field NotificationEmail to the POST /v1/ComplianceInquiries/Customers/Initialize API +- Add additional optional fields in compliance_tollfree_inquiry.json +- Rename did to tollfree_phone_number in compliance_tollfree_inquiry.json +- Add new optional field notification_email to compliance_tollfree_inquiry.json + +**Verify** +- `Tags` property added again to Public Docs **(breaking change)** +- Remove `Tags` from Public Docs **(breaking change)** +- Add `VerifyEventSubscriptionEnabled` parameter to service create and update endpoints. +- Add `Tags` optional parameter on Verification creation. +- Update Verify TOTP maturity to GA. + + +[2024-01-25] Version 8.12.0 +--------------------------- +**Oauth** +- updated openid discovery endpoint uri **(breaking change)** +- Added device code authorization endpoint +- added oauth JWKS endpoint +- Get userinfo resource +- OpenID discovery resource +- Add new API for token endpoint + + +[2024-01-14] Version 8.11.1 +--------------------------- +**Library - Chore** +- [PR #749](https://github.com/twilio/twilio-python/pull/749): removing webhook test. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Push** +- Migrated to new Push API V4 with Resilient Notification Delivery. + + +[2023-12-14] Version 8.11.0 +--------------------------- +**Library - Chore** +- [PR #741](https://github.com/twilio/twilio-python/pull/741): upgrade to python 3.12. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #740](https://github.com/twilio/twilio-python/pull/740): bump aiohttp. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Api** +- Updated service base url for connect apps and authorized connect apps APIs **(breaking change)** + +**Events** +- Marked as GA + +**Insights** +- decommission voice-qualitystats-endpoint role + +**Numbers** +- Add Get Port In request api + +**Taskrouter** +- Add `jitter_buffer_size` param in update reservation + +**Trusthub** +- Add additional optional fields in compliance_tollfree_inquiry.json + +**Verify** +- Remove `Tags` from Public Docs **(breaking change)** + + +[2023-12-01] Version 8.10.3 +--------------------------- +**Verify** +- Add `VerifyEventSubscriptionEnabled` parameter to service create and update endpoints. + + +[2023-11-17] Version 8.10.2 +--------------------------- +**Library - Chore** +- [PR #733](https://github.com/twilio/twilio-python/pull/733): bumping aiohttp from 3.8.5 to 3.8.6. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Api** +- Update documentation to reflect RiskCheck GA + +**Messaging** +- Add tollfree edit_allowed and edit_reason fields +- Update Phone Number, Short Code, Alpha Sender, US A2P and Channel Sender documentation + +**Taskrouter** +- Add container attribute to task_queue_bulk_real_time_statistics endpoint + +**Trusthub** +- Rename did to tollfree_phone_number in compliance_tollfree_inquiry.json +- Add new optional field notification_email to compliance_tollfree_inquiry.json + +**Verify** +- Add `Tags` optional parameter on Verification creation. + + +[2023-11-06] Version 8.10.1 +--------------------------- +**Flex** +- Adding `provisioning_status` for Email Manager + +**Intelligence** +- Add text-generation operator (for example conversation summary) results to existing OperatorResults collection. + +**Messaging** +- Add DELETE support to Tollfree Verification resource + +**Serverless** +- Add node18 as a valid Build runtime + +**Verify** +- Update Verify TOTP maturity to GA. + + +[2023-10-19] Version 8.10.0 +--------------------------- +**Library - Fix** +- [PR #730](https://github.com/twilio/twilio-python/pull/730): Requirement changes. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #727](https://github.com/twilio/twilio-python/pull/727): Requirement changes. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #726](https://github.com/twilio/twilio-python/pull/726): requirements changes. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Accounts** +- Updated Safelist metadata to correct the docs. +- Add Global SafeList API changes + +**Api** +- Added optional parameter `CallToken` for create participant api + +**Flex** +- Adding `offline_config` to Flex Configuration + +**Intelligence** +- Deleted `redacted` parameter from fetching transcript in v2 **(breaking change)** + +**Lookups** +- Add new `phone_number_quality_score` package to the lookup response +- Remove `disposable_phone_number_risk` package **(breaking change)** + +**Messaging** +- Update US App To Person documentation with current `message_samples` requirements + +**Taskrouter** +- Remove beta_feature check on task_queue_bulk_real_time_statistics endpoint +- Add `virtual_start_time` property to tasks +- Updating `task_queue_data` format from `map` to `array` in the response of bulk get endpoint of TaskQueue Real Time Statistics API **(breaking change)** + + +[2023-10-05] Version 8.9.1 +-------------------------- +**Library - Chore** +- [PR #721](https://github.com/twilio/twilio-python/pull/721): Drop dependency on `pytz` by using stdlib `datetime.timezone.utc`. Thanks to [@Zac-HD](https://github.com/Zac-HD)! +- [PR #723](https://github.com/twilio/twilio-python/pull/723): twilio help changes. Thanks to [@kridai](https://github.com/kridai)! + +**Library - Fix** +- [PR #724](https://github.com/twilio/twilio-python/pull/724): Update ValidateSslCertificate method. Thanks to [@AsabuHere](https://github.com/AsabuHere)! + +**Lookups** +- Add test api support for Lookup v2 + + +[2023-09-21] Version 8.9.0 +-------------------------- +**Conversations** +- Enable conversation email bindings, email address configurations and email message subjects + +**Flex** +- Adding `console_errors_included` to Flex Configuration field `debugger_integrations` +- Introducing new channel status as `inactive` in modify channel endpoint for leave functionality **(breaking change)** +- Adding `citrix_voice_vdi` to Flex Configuration + +**Taskrouter** +- Add Update Queues, Workers, Workflow Real Time Statistics API to flex-rt-data-api-v2 endpoint +- Add Update Workspace Real Time Statistics API to flex-rt-data-api-v2 endpoint + + +[2023-09-07] Version 8.8.0 +-------------------------- +**Api** +- Make message tagging parameters public **(breaking change)** + +**Flex** +- Adding `agent_conv_end_methods` to Flex Configuration + +**Messaging** +- Mark Mesasging Services fallback_to_long_code feature obsolete + +**Numbers** +- Add Create Port In request api +- Renaming sid for bulk_hosting_sid and remove account_sid response field in numbers/v2/BulkHostedNumberOrders **(breaking change)** + +**Pricing** +- gate resources behind a beta_feature + + +[2023-08-24] Version 8.7.0 +-------------------------- +**Library - Test** +- [PR #719](https://github.com/twilio/twilio-python/pull/719): Update test_webhook.py. Thanks to [@kridai](https://github.com/kridai)! + +**Api** +- Add new property `RiskCheck` for SMS pumping protection feature only (public beta to be available soon): Include this parameter with a value of `disable` to skip any kind of risk check on the respective message request + +**Flex** +- Changing `sid` path param to `sid` in interaction channel participant update endpoint **(breaking change)** + +**Messaging** +- Add Channel Sender api +- Fixing country code docs and removing Zipwhip references + +**Numbers** +- Request status changed in numbers/v2/BulkHostedNumberOrders **(breaking change)** +- Add bulk hosting orders API under version `/v2 + + +[2023-08-10] Version 8.6.0 +-------------------------- +**Insights** +- Normalize annotations parameters in list summary api to be prefixed + +**Numbers** +- Change Bulk_hosted_sid from BHR to BH prefix in HNO and dependent under version `/v2` API's. **(breaking change)** +- Added parameter target_account_sid to portability and account_sid to response body + +**Verify** +- Remove beta feature flag to list attempts API. +- Remove beta feature flag to verifications summary attempts API. + + +[2023-07-27] Version 8.5.1 +-------------------------- +**Api** +- Added `voice-intelligence`, `voice-intelligence-transcription` and `voice-intelligence-operators` to `usage_record` API. +- Added `tts-google` to `usage_record` API. + +**Lookups** +- Add new `disposable_phone_number_risk` package to the lookup response + +**Verify** +- Documentation of list attempts API was improved by correcting `date_created_after` and `date_created_before` expected date format. +- Documentation was improved by correcting `date_created_after` and `date_created_before` expected date format parameter on attempts summary API. +- Documentation was improved by adding `WHATSAPP` as optional valid parameter on attempts summary API. + +**Twiml** +- Added support for he-il inside of ssm_lang.json that was missing +- Added support for he-il language in say.json that was missing +- Add `statusCallback` and `statusCallbackMethod` attributes to ``. + + +[2023-07-13] Version 8.5.0 +-------------------------- +**Library - Fix** +- [PR #718](https://github.com/twilio/twilio-python/pull/718): Create __init__.py for intelligence domain. Thanks to [@AsabuHere](https://github.com/AsabuHere)! + +**Flex** +- Adding `interaction_context_sid` as optional parameter in Interactions API + +**Messaging** +- Making visiblity public for tollfree_verification API + +**Numbers** +- Remove Sms capability property from HNO creation under version `/v2` of HNO API. **(breaking change)** +- Update required properties in LOA creation under version `/v2` of Authorization document API. **(breaking change)** + +**Taskrouter** +- Add api to fetch task queue statistics for multiple TaskQueues + +**Verify** +- Add `RiskCheck` optional parameter on Verification creation. + +**Twiml** +- Add Google Voices and languages + + +[2023-06-28] Version 8.4.0 +-------------------------- +**Lookups** +- Add `reassigned_number` package to the lookup response + +**Numbers** +- Add hosted_number_order under version `/v2`. +- Update properties in Porting and Bulk Porting APIs. **(breaking change)** +- Added bulk Portability API under version `/v1`. +- Added Portability API under version `/v1`. + + +[2023-06-15] Version 8.3.0 +-------------------------- +**Api** +- Added `content_sid` as conditional parameter +- Removed `content_sid` as optional field **(breaking change)** + +**Insights** +- Added `annotation` to list summary output + + +[2023-06-01] Version 8.2.2 +-------------------------- +**Api** +- Add `Trim` to create Conference Participant API + +**Intelligence** +- First public beta release for Voice Intelligence APIs with client libraries + +**Messaging** +- Add new `errors` attribute to us_app_to_person resource. This attribute will provide additional information about campaign registration errors. + + +[2023-05-18] Version 8.2.1 +-------------------------- +**Conversations** +- Added `AddressCountry` parameter to Address Configuration endpoint, to support regional short code addresses +- Added query parameters `start_date`, `end_date` and `state` in list Conversations resource for filtering + +**Insights** +- Added annotations parameters to list summary api + +**Messaging** +- Add GET domainByMessagingService endpoint to linkShortening service +- Add `disable_https` to link shortening domain_config properties + +**Numbers** +- Add bulk_eligibility api under version `/v1`. + + +[2023-05-04] Version 8.2.0 +-------------------------- +**Conversations** +- Remove `start_date`, `end_date` and `state` query parameters from list operation on Conversations resource **(breaking change)** + +**Twiml** +- Add support for new Amazon Polly voices (Q1 2023) for `Say` verb + + +[2023-04-19] Version 8.1.0 +-------------------------- +**Library - Chore** +- [PR #709](https://github.com/twilio/twilio-python/pull/709): Drop `asyncio` from requirements. Thanks to [@setu4993](https://github.com/setu4993)! + +**Library - Docs** +- [PR #705](https://github.com/twilio/twilio-python/pull/705): consolidate. Thanks to [@stern-shawn](https://github.com/stern-shawn)! + +**Messaging** +- Remove `messaging_service_sids` and `messaging_service_sid_action` from domain config endpoint **(breaking change)** +- Add error_code and rejection_reason properties to tollfree verification API response + +**Numbers** +- Added the new Eligibility API under version `/v1`. + + +[2023-04-05] Version 8.0.0 +-------------------------- +**Note:** This release contains breaking changes, check our [upgrade guide](./UPGRADE.md###-2023-04-05-7xx-to-8xx) for detailed migration notes. + +**Library - Feature** +- [PR #702](https://github.com/twilio/twilio-python/pull/702): Merge branch '8.0.0-rc' to main. Thanks to [@childish-sambino](https://github.com/childish-sambino)! **(breaking change)** + +**Conversations** +- Expose query parameters `start_date`, `end_date` and `state` in list operation on Conversations resource for sorting and filtering + +**Insights** +- Added answered by filter in Call Summaries + +**Lookups** +- Remove `disposable_phone_number_risk` package **(breaking change)** + +**Messaging** +- Add support for `SOLE_PROPRIETOR` brand type and `SOLE_PROPRIETOR` campaign use case. +- New Sole Proprietor Brands should be created with `SOLE_PROPRIETOR` brand type. Brand registration requests with `STARTER` brand type will be rejected. +- New Sole Proprietor Campaigns should be created with `SOLE_PROPRIETOR` campaign use case. Campaign registration requests with `STARTER` campaign use case will be rejected. +- Add Brand Registrations OTP API + + +[2023-03-22] Version 7.17.0 +--------------------------- +**Api** +- Revert Corrected the data type for `friendly_name` in Available Phone Number Local, Mobile and TollFree resources +- Corrected the data type for `friendly_name` in Available Phone Number Local, Mobile and TollFree resources **(breaking change)** + +**Messaging** +- Add `linkshortening_messaging_service` resource +- Add new endpoint for GetDomainConfigByMessagingServiceSid +- Remove `validated` parameter and add `cert_in_validation` parameter to Link Shortening API **(breaking change)** + + +[2023-03-09] Version 7.16.5 +--------------------------- +**Api** +- Add new categories for whatsapp template + +**Lookups** +- Remove `validation_results` from the `default_output_properties` + +**Supersim** +- Add ESimProfile's `matching_id` and `activation_code` parameters to libraries + + +[2023-02-22] Version 7.16.4 +--------------------------- +**Api** +- Remove `scheduled_for` property from message resource +- Add `scheduled_for` property to message resource + + +[2023-02-08] Version 7.16.3 +--------------------------- +**Lookups** +- Add `disposable_phone_number_risk` package to the lookup response +- Add `sms_pumping_risk` package to the lookup response + + +[2023-01-25] Version 7.16.2 +--------------------------- +**Library - Chore** +- [PR #638](https://github.com/twilio/twilio-python/pull/638): relax test dependencies and remove unused dependencies. Thanks to [@childish-sambino](https://github.com/childish-sambino)! +- [PR #609](https://github.com/twilio/twilio-python/pull/609): Security upgrade pygments from 2.5.2 to 2.7.4. Thanks to [@twilio-product-security](https://github.com/twilio-product-security)! + +**Library - Docs** +- [PR #637](https://github.com/twilio/twilio-python/pull/637): remove docs output from repo. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Library - Test** +- [PR #636](https://github.com/twilio/twilio-python/pull/636): update tox config and replace deprecated test functions. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Add `public_application_connect_enabled` param to Application resource + +**Messaging** +- Add new tollfree verification API property (ExternalReferenceId)] + +**Verify** +- Add `device_ip` parameter and channel `auto` for sna/sms orchestration + +**Twiml** +- Add support for `` noun and `` noun, nested `` to `` and `` verb + + +[2023-01-11] Version 7.16.1 +--------------------------- +**Conversations** +- Add support for creating Multi-Channel Rich Content Messages + +**Lookups** +- Changed the no data message for match postal code from `no_data` to `data_not_available` in identity match package + +**Messaging** +- Add update/edit tollfree verification API + + +[2022-12-14] Version 7.16.0 +--------------------------- +**Library - Docs** +- [PR #631](https://github.com/twilio/twilio-python/pull/631): Updated docstrings for timeout to be float instead of int. Thanks to [@byarmis](https://github.com/byarmis)! + +**Library - Chore** +- [PR #627](https://github.com/twilio/twilio-python/pull/627): add support for python 3.11. Thanks to [@JenniferMah](https://github.com/JenniferMah)! + +**Library - Test** +- [PR #628](https://github.com/twilio/twilio-python/pull/628): Pinning ubuntu version for python 3.6 test runs. Thanks to [@rakatyal](https://github.com/rakatyal)! + +**Api** +- Add `street_secondary` param to address create and update +- Make `method` optional for user defined message subscription **(breaking change)** + +**Flex** +- Flex Conversations is now Generally Available +- Adding the ie1 mapping for authorization api, updating service base uri and base url response attribute **(breaking change)** +- Change web channels to GA and library visibility to public +- Changing the uri for authorization api from using Accounts to Insights **(breaking change)** + +**Media** +- Gate Twilio Live endpoints behind beta_feature for EOS + +**Messaging** +- Mark `MessageFlow` as a required field for Campaign Creation **(breaking change)** + +**Oauth** +- updated openid discovery endpoint uri **(breaking change)** +- Added device code authorization endpoint + +**Supersim** +- Allow filtering the SettingsUpdates resource by `status` + +**Twiml** +- Add new Polly Neural voices +- Add tr-TR, ar-AE, yue-CN, fi-FI languages to SSML `` element. +- Add x-amazon-jyutping, x-amazon-pinyin, x-amazon-pron-kana, x-amazon-yomigana alphabets to SSML `` element. +- Rename `character` value for SSML `` `interpret-as` attribute to `characters`. **(breaking change)** +- Rename `role` attribute to `format` in SSML `` element. **(breaking change)** + + +[2022-11-30] Version 7.15.4 +--------------------------- +**Flex** +- Adding new `assessments` api in version `v1` + +**Lookups** +- Add `identity_match` package to the lookup response + +**Messaging** +- Added `validated` parameter to Link Shortening API + +**Serverless** +- Add node16 as a valid Build runtime +- Add ie1 and au1 as supported regions for all endpoints. + + +[2022-11-16] Version 7.15.3 +--------------------------- +**Library - Chore** +- [PR #624](https://github.com/twilio/twilio-python/pull/624): upgrade GitHub Actions dependencies. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Set the Content resource to have public visibility as Preview + +**Flex** +- Adding new parameter `base_url` to 'gooddata' response in version `v1` + +**Insights** +- Added `answered_by` field in List Call Summary +- Added `answered_by` field in call summary + + +[2022-11-10] Version 7.15.2 +--------------------------- +**Flex** +- Adding two new authorization API 'user_roles' and 'gooddata' in version `v1` + +**Messaging** +- Add new Campaign properties (MessageFlow, OptInMessage, OptInKeywords, OptOutMessage, OptOutKeywords, HelpMessage, HelpKeywords) + +**Twiml** +- Add new speech models to `Gather`. + + +[2022-10-31] Version 7.15.1 +--------------------------- +**Api** +- Added `contentSid` and `contentVariables` to Message resource with public visibility as Beta +- Add `UserDefinedMessageSubscription` and `UserDefinedMessage` resource + +**Proxy** +- Remove FailOnParticipantConflict param from Proxy Session create and update and Proxy Participant create + +**Supersim** +- Update SettingsUpdates resource to remove PackageSid + +**Taskrouter** +- Add `Ordering` query parameter to Workers and TaskQueues for sorting by +- Add `worker_sid` query param for list reservations endpoint + +**Twiml** +- Add `url` and `method` attributes to `` + + +[2022-10-19] Version 7.15.0 +--------------------------- +**Api** +- Make link shortening parameters public **(breaking change)** + +**Oauth** +- added oauth JWKS endpoint +- Get userinfo resource +- OpenID discovery resource +- Add new API for token endpoint + +**Supersim** +- Add SettingsUpdates resource + +**Verify** +- Update Verify Push endpoints to `ga` maturity +- Verify BYOT add Channels property to the Get Templates response + +**Twiml** +- Add `requireMatchingInputs` attribute and `input-matching-failed` errorType to `` + + +[2022-10-05] Version 7.14.2 +--------------------------- +**Api** +- Added `virtual-agent` to `usage_record` API. +- Add AMD attributes to participant create request + +**Twiml** +- Add AMD attributes to `Number` and `Sip` + + +[2022-09-21] Version 7.14.1 +--------------------------- +**Library - Fix** +- [PR #617](https://github.com/twilio/twilio-python/pull/617): support duplicated query param values. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + + +[2022-09-07] Version 7.14.0 +--------------------------- +**Library - Fix** +- [PR #615](https://github.com/twilio/twilio-python/pull/615): support duplicate query param values. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Flex** +- Removed redundant `close` status from Flex Interactions flow **(breaking change)** +- Adding `debugger_integration` and `flex_ui_status_report` to Flex Configuration + +**Messaging** +- Add create, list and get tollfree verification API + +**Verify** +- Verify SafeList API endpoints added. + +**Video** +- Add `Anonymize` API + +**Twiml** +- Update `event` value `call-in-progress` to `call-answered` + + +[2022-08-24] Version 7.13.0 +--------------------------- +**Library - Test** +- [PR #614](https://github.com/twilio/twilio-python/pull/614): add test-docker rule. Thanks to [@beebzz](https://github.com/beebzz)! + +**Api** +- Remove `beta feature` from scheduling params and remove optimize parameters. **(breaking change)** + +**Routes** +- Remove Duplicate Create Method - Update Method will work even if Inbound Processing Region is currently empty/404. **(breaking change)** + +**Twiml** +- Add new Polly Neural voices +- Add new languages to SSML ``. + + +[2022-08-10] Version 7.12.1 +--------------------------- +**Routes** +- Inbound Proccessing Region API - Public GA + +**Supersim** +- Allow updating `DataLimit` on a Fleet + + +[2022-07-21] Version 7.12.0 +--------------------------- +**Flex** +- Add `status`, `error_code`, and `error_message` fields to Interaction `Channel` +- Adding `messenger` and `gbm` as supported channels for Interactions API + +**Messaging** +- Update alpha_sender docs with new valid characters + +**Verify** +- Reorder Verification Check parameters so `code` stays as the first parameter **(breaking change)** +- Rollback List Attempts API V2 back to pilot stage. + + +[2022-07-13] Version 7.11.0 +--------------------------- +**Library - Fix** +- [PR #611](https://github.com/twilio/twilio-python/pull/611): useragent regrex unit test for RC branch. Thanks to [@claudiachua](https://github.com/claudiachua)! + +**Library - Test** +- [PR #610](https://github.com/twilio/twilio-python/pull/610): Adding misc as PR type. Thanks to [@rakatyal](https://github.com/rakatyal)! + +**Conversations** +- Allowed to use `identity` as part of Participant's resource **(breaking change)** + +**Lookups** +- Remove `enhanced_line_type` from the lookup response **(breaking change)** + +**Supersim** +- Add support for `sim_ip_addresses` resource to helper libraries + +**Verify** +- Changed summary param `service_sid` to `verify_service_sid` to be consistent with list attempts API **(breaking change)** +- Make `code` optional on Verification check to support `sna` attempts. **(breaking change)** + + +[2022-06-29] Version 7.10.0 +--------------------------- +**Api** +- Added `amazon-polly` to `usage_record` API. + +**Insights** +- Added `annotation` field in call summary +- Added new endpoint to fetch/create/update Call Annotations + +**Verify** +- Remove `api.verify.totp` beta flag and set maturity to `beta` for Verify TOTP properties and parameters. **(breaking change)** +- Changed summary param `verify_service_sid` to `service_sid` to be consistent with list attempts API **(breaking change)** + +**Twiml** +- Add `maxQueueSize` to `Enqueue` + + +[2022-06-15] Version 7.9.3 +-------------------------- +**Lookups** +- Adding support for Lookup V2 API + +**Studio** +- Corrected PII labels to be 30 days and added context to be PII + +**Twiml** +- Add `statusCallbackMethod` attribute, nested `` elements to `` noun. +- Add support for new Amazon Polly voices (Q2 2022) for `Say` verb +- Add support for `` noun + + +[2022-06-01] Version 7.9.2 +-------------------------- +**Library - Chore** +- [PR #608](https://github.com/twilio/twilio-python/pull/608): use Docker 'rc' tag for release candidate images. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + + +[2022-05-18] Version 7.9.1 +-------------------------- +**Library - Fix** +- [PR #592](https://github.com/twilio/twilio-python/pull/592): Respect HTTPS_PROXY and other settings from env vars. Thanks to [@AlanCoding](https://github.com/AlanCoding)! + +**Api** +- Add property `media_url` to the recording resources + +**Verify** +- Include `silent` as a channel type in the verifications API. + + +[2022-05-04] Version 7.9.0 +-------------------------- +**Conversations** +- Expose query parameter `type` in list operation on Address Configurations resource + +**Supersim** +- Add `data_total_billed` and `billed_units` fields to Super SIM UsageRecords API response. +- Change ESimProfiles `Eid` parameter to optional to enable Activation Code download method support **(breaking change)** + +**Verify** +- Deprecate `push.include_date` parameter in create and update service. + + +[2022-04-20] Version 7.8.2 +-------------------------- +**Library - Fix** +- [PR #601](https://github.com/twilio/twilio-python/pull/601): Fixing logging of http request and response. Thanks to [@rakatyal](https://github.com/rakatyal)! + + +[2022-04-06] Version 7.8.1 +-------------------------- +**Library - Chore** +- [PR #600](https://github.com/twilio/twilio-python/pull/600): add jinja2 for make docs. Thanks to [@JenniferMah](https://github.com/JenniferMah)! +- [PR #599](https://github.com/twilio/twilio-python/pull/599): DI-1565 test case. Thanks to [@claudiachua](https://github.com/claudiachua)! +- [PR #597](https://github.com/twilio/twilio-python/pull/597): update user-agent string to standardize format. Thanks to [@claudiachua](https://github.com/claudiachua)! + +**Library - Fix** +- [PR #593](https://github.com/twilio/twilio-python/pull/593): revise malformed __str__(self) function. Thanks to [@twilio-aiss](https://github.com/twilio-aiss)! + +**Api** +- Updated `provider_sid` visibility to private + +**Verify** +- Verify List Attempts API summary endpoint added. +- Update PII documentation for `AccessTokens` `factor_friendly_name` property. + +**Voice** +- make annotation parameter from /Calls API private + + +[2022-03-23] Version 7.8.0 +-------------------------- +**Api** +- Change `stream` url parameter to non optional +- Add `verify-totp` and `verify-whatsapp-conversations-business-initiated` categories to `usage_record` API + +**Chat** +- Added v3 Channel update endpoint to support Public to Private channel migration + +**Flex** +- Private Beta release of the Interactions API to support the upcoming release of Flex Conversations at the end of Q1 2022. +- Adding `channel_configs` object to Flex Configuration + +**Media** +- Add max_duration param to PlayerStreamer + +**Supersim** +- Remove Commands resource, use SmsCommands resource instead **(breaking change)** + +**Taskrouter** +- Add limits to `split_by_wait_time` for Cumulative Statistics Endpoint + +**Video** +- Change recording `status_callback_method` type from `enum` to `http_method` **(breaking change)** +- Add `status_callback` and `status_callback_method` to composition +- Add `status_callback` and `status_callback_method` to recording + + +[2022-03-09] Version 7.7.1 +-------------------------- +**Library - Chore** +- [PR #591](https://github.com/twilio/twilio-python/pull/591): push Datadog Release Metric upon deploy success. Thanks to [@eshanholtz](https://github.com/eshanholtz)! + +**Api** +- Add optional boolean include_soft_deleted parameter to retrieve soft deleted recordings + +**Chat** +- Add `X-Twilio-Wehook-Enabled` header to `delete` method in UserChannel resource + +**Numbers** +- Expose `failure_reason` in the Supporting Documents resources + +**Verify** +- Add optional `metadata` parameter to "verify challenge" endpoint, so the SDK/App can attach relevant information from the device when responding to challenges. +- remove beta feature flag to list atempt api operations. +- Add `ttl` and `date_created` properties to `AccessTokens`. + + +[2022-02-23] Version 7.7.0 +-------------------------- +**Api** +- Add `uri` to `stream` resource +- Add A2P Registration Fee category (`a2p-registration-fee`) to usage records +- Detected a bug and removed optional boolean include_soft_deleted parameter to retrieve soft deleted recordings. **(breaking change)** +- Add optional boolean include_soft_deleted parameter to retrieve soft deleted recordings. + +**Numbers** +- Unrevert valid_until and sort filter params added to List Bundles resource +- Revert valid_until and sort filter params added to List Bundles resource +- Update sorting params added to List Bundles resource in the previous release + +**Preview** +- Moved `web_channels` from preview to beta under `flex-api` **(breaking change)** + +**Taskrouter** +- Add `ETag` as Response Header to List of Task, Reservation & Worker + +**Verify** +- Remove outdated documentation commentary to contact sales. Product is already in public beta. +- Add optional `metadata` to factors. + +**Twiml** +- Add new Polly Neural voices + + +[2022-02-09] Version 7.6.0 +-------------------------- +**Library - Chore** +- [PR #589](https://github.com/twilio/twilio-python/pull/589): upgrade supported language versions. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Library - Test** +- [PR #588](https://github.com/twilio/twilio-python/pull/588): migrate to pytest for python 3.10 compatibility. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Add `stream` resource + +**Conversations** +- Fixed DELETE request to accept "sid_like" params in Address Configuration resources **(breaking change)** +- Expose Address Configuration resource for `sms` and `whatsapp` + +**Fax** +- Removed deprecated Programmable Fax Create and Update methods **(breaking change)** + +**Insights** +- Rename `call_state` to `call_status` and remove `whisper` in conference participant summary **(breaking change)** + +**Numbers** +- Expose valid_until filters as part of provisionally-approved compliance feature on the List Bundles resource + +**Supersim** +- Fix typo in Fleet resource docs +- Updated documentation for the Fleet resource indicating that fields related to commands have been deprecated and to use sms_command fields instead. +- Add support for setting and reading `ip_commands_url` and `ip_commands_method` on Fleets resource for helper libraries +- Changed `sim` property in requests to create an SMS Command made to the /SmsCommands to accept SIM UniqueNames in addition to SIDs + +**Verify** +- Update list attempts API to include new filters and response fields. + + +[2022-01-26] Version 7.5.1 +-------------------------- +**Insights** +- Added new endpoint to fetch Conference Participant Summary +- Added new endpoint to fetch Conference Summary + +**Messaging** +- Add government_entity parameter to brand apis + +**Verify** +- Add Access Token fetch endpoint to retrieve a previously created token. +- Add Access Token payload to the Access Token creation endpoint, including a unique Sid, so it's addressable while it's TTL is valid. + + +[2022-01-12] Version 7.5.0 +-------------------------- +**Library - Chore** +- [PR #587](https://github.com/twilio/twilio-python/pull/587): add sonarcloud integration. Thanks to [@BrimmingDev](https://github.com/BrimmingDev)! + +**Library - Feature** +- [PR #586](https://github.com/twilio/twilio-python/pull/586): add GitHub release step during deploy. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Make fixed time scheduling parameters public **(breaking change)** + +**Messaging** +- Add update brand registration API + +**Numbers** +- Add API endpoint for List Bundle Copies resource + +**Video** +- Enable external storage for all customers + + +[2021-12-15] Version 7.4.0 +-------------------------- +**Library - Feature** +- [PR #582](https://github.com/twilio/twilio-python/pull/582): run tests before deploying. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Add optional boolean send_as_mms parameter to the create action of Message resource **(breaking change)** +- Change team ownership for `call` delete + +**Conversations** +- Change wording for `Service Webhook Configuration` resource fields + +**Insights** +- Added new APIs for updating and getting voice insights flags by accountSid. + +**Media** +- Add max_duration param to MediaProcessor + +**Video** +- Add `EmptyRoomTimeout` and `UnusedRoomTimeout` properties to a room; add corresponding parameters to room creation + +**Voice** +- Add endpoint to delete archived Calls + + +[2021-12-01] Version 7.3.2 +-------------------------- +**Conversations** +- Add `Service Webhook Configuration` resource + +**Flex** +- Adding `flex_insights_drilldown` and `flex_url` objects to Flex Configuration + +**Messaging** +- Update us_app_to_person endpoints to remove beta feature flag based access + +**Supersim** +- Add IP Commands resource + +**Verify** +- Add optional `factor_friendly_name` parameter to the create access token endpoint. + +**Video** +- Add maxParticipantDuration param to Rooms + +**Twiml** +- Unrevert Add supported SSML children to ``, ``, `

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

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

`, ``, ``, and ``. + + +[2021-11-03] Version 7.3.0 +-------------------------- +**Library - Chore** +- [PR #577](https://github.com/twilio/twilio-python/pull/577): migrate from travis ci to gh actions. Thanks to [@shwetha-manvinkurke](https://github.com/shwetha-manvinkurke)! + +**Api** +- Updated `media_url` property to be treated as PII + +**Messaging** +- Added a new enum for brand registration status named DELETED **(breaking change)** +- Add a new K12_EDUCATION use case in us_app_to_person_usecase api transaction +- Added a new enum for brand registration status named IN_REVIEW + +**Serverless** +- Add node14 as a valid Build runtime + +**Verify** +- Fix typos in Verify Push Factor documentation for the `config.notification_token` parameter. +- Added `TemplateCustomSubstitutions` on verification creation +- Make `TemplateSid` parameter public for Verification resource and `DefaultTemplateSid` parameter public for Service resource. **(breaking change)** + + +[2021-10-18] Version 7.2.0 +-------------------------- +**Library - Feature** +- [PR #576](https://github.com/twilio/twilio-python/pull/576): Add PlaybackGrant. Thanks to [@sarahcstringer](https://github.com/sarahcstringer)! + +**Api** +- Corrected enum values for `emergency_address_status` values in `/IncomingPhoneNumbers` response. **(breaking change)** +- Clarify `emergency_address_status` values in `/IncomingPhoneNumbers` response. + +**Messaging** +- Add PUT and List brand vettings api +- Removes beta feature flag based visibility for us_app_to_person_registered and usecase field.Updates test cases to add POLITICAL usecase. **(breaking change)** +- Add brand_feedback as optional field to BrandRegistrations + +**Video** +- Add `AudioOnly` to create room + + +[2021-10-06] Version 7.1.0 +-------------------------- +**Api** +- Add `emergency_address_status` attribute to `/IncomingPhoneNumbers` response. +- Add `siprec` resource + +**Conversations** +- Added attachment parameters in configuration for `NewMessage` type of push notifications + +**Flex** +- Adding `flex_insights_hr` object to Flex Configuration + +**Numbers** +- Add API endpoint for Bundle ReplaceItems resource +- Add API endpoint for Bundle Copies resource + +**Serverless** +- Add domain_base field to Service response + +**Taskrouter** +- Add `If-Match` Header based on ETag for Worker Delete **(breaking change)** +- Add `If-Match` Header based on Etag for Reservation Update +- Add `If-Match` Header based on ETag for Worker Update +- Add `If-Match` Header based on ETag for Worker Delete +- Add `ETag` as Response Header to Worker + +**Trunking** +- Added `transfer_caller_id` property on Trunks. + +**Verify** +- Document new pilot `whatsapp` channel. + + +[2021-09-22] Version 7.0.0 +-------------------------- +**Note:** This release contains breaking changes, check our [upgrade guide](./UPGRADE.md#2021-09-22-6xx-to-7xx) for detailed migration notes. + +**Library - Fix** +- [PR #560](https://github.com/twilio/twilio-python/pull/560): update code and tests for pyjwt>=2.0.0. Thanks to [@karls](https://github.com/karls)! **(breaking change)** + +**Library - Docs** +- [PR #570](https://github.com/twilio/twilio-python/pull/570): Add upgrade guide for dropping python 2.7, 3.4 & 3.5. Thanks to [@JenniferMah](https://github.com/JenniferMah)! + +**Events** +- Add segment sink + +**Messaging** +- Add post_approval_required attribute in GET us_app_to_person_usecase api response +- Add Identity Status, Russell 3000, Tax Exempt Status and Should Skip SecVet fields for Brand Registrations +- Add Should Skip Secondary Vetting optional flag parameter to create Brand API + + +[2021-09-08] Version 6.63.2 +--------------------------- +**Api** +- Revert adding `siprec` resource +- Add `siprec` resource + +**Messaging** +- Add 'mock' as an optional field to brand_registration api +- Add 'mock' as an optional field to us_app_to_person api +- Adds more Use Cases in us_app_to_person_usecase api transaction and updates us_app_to_person_usecase docs + +**Verify** +- Verify List Templates API endpoint added. + + +[2021-08-25] Version 6.63.1 +--------------------------- +**Api** +- Add Programmabled Voice SIP Refer call transfers (`calls-transfers`) to usage records +- Add Flex Voice Usage category (`flex-usage`) to usage records + +**Conversations** +- Add `Order` query parameter to Message resource read operation + +**Insights** +- Added `partial` to enum processing_state_request +- Added abnormal session filter in Call Summaries + +**Messaging** +- Add brand_registration_sid as an optional query param for us_app_to_person_usecase api + +**Pricing** +- add trunking_numbers resource (v2) +- add trunking_country resource (v2) + +**Verify** +- Changed to private beta the `TemplateSid` optional parameter on Verification creation. +- Added the optional parameter `Order` to the list Challenges endpoint to define the list order. + + +[2021-08-11] Version 6.63.0 +--------------------------- +**Library - Fix** +- [PR #572](https://github.com/twilio/twilio-python/pull/572): fix sonar analysis. Thanks to [@shwetha-manvinkurke](https://github.com/shwetha-manvinkurke)! + +**Library - Chore** +- [PR #571](https://github.com/twilio/twilio-python/pull/571): integrate with sonarcloud. Thanks to [@shwetha-manvinkurke](https://github.com/shwetha-manvinkurke)! + +**Api** +- Corrected the `price`, `call_sid_to_coach`, and `uri` data types for Conference, Participant, and Recording **(breaking change)** +- Made documentation for property `time_limit` in the call api public. **(breaking change)** +- Added `domain_sid` in sip_credential_list_mapping and sip_ip_access_control_list_mapping APIs **(breaking change)** + +**Insights** +- Added new endpoint to fetch Call Summaries + +**Messaging** +- Add brand_type field to a2p brand_registration api +- Revert brand registration api update to add brand_type field +- Add brand_type field to a2p brand_registration api + +**Taskrouter** +- Add `X-Rate-Limit-Limit`, `X-Rate-Limit-Remaining`, and `X-Rate-Limit-Config` as Response Headers to all TaskRouter endpoints + +**Verify** +- Add `TemplateSid` optional parameter on Verification creation. +- Include `whatsapp` as a channel type in the verifications API. + + +[2021-07-28] Version 6.62.1 +--------------------------- +**Conversations** +- Expose ParticipantConversations resource + +**Taskrouter** +- Adding `links` to the activity resource + +**Verify** +- Added a `Version` to Verify Factors `Webhooks` to add new fields without breaking old Webhooks. + + +[2021-07-14] Version 6.62.0 +--------------------------- +**Conversations** +- Changed `last_read_message_index` and `unread_messages_count` type in User Conversation's resource **(breaking change)** +- Expose UserConversations resource + +**Messaging** +- Add brand_score field to brand registration responses + + +[2021-06-30] Version 6.61.0 +--------------------------- +**Conversations** +- Read-only Conversation Email Binding property `binding` + +**Supersim** +- Add Billing Period resource for the Super Sim Pilot +- Add List endpoint to Billing Period resource for Super Sim Pilot +- Add Fetch endpoint to Billing Period resource for Super Sim Pilot + +**Taskrouter** +- Update `transcribe` & `transcription_configuration` form params in Reservation update endpoint to have private visibility **(breaking change)** +- Add `transcribe` & `transcription_configuration` form params to Reservation update endpoint + +**Twiml** +- Add `modify` event to `statusCallbackEvent` for ``. + + +[2021-06-16] Version 6.60.0 +--------------------------- +**Api** +- Update `status` enum for Messages to include 'canceled' +- Update `update_status` enum for Messages to include 'canceled' + +**Trusthub** +- Corrected the sid for policy sid in customer_profile_evaluation.json and trust_product_evaluation.json **(breaking change)** + + +[2021-06-02] Version 6.59.1 +--------------------------- +**Events** +- join Sinks and Subscriptions service + +**Verify** +- Improved the documentation of `challenge` adding the maximum and minimum expected lengths of some fields. +- Improve documentation regarding `notification` by updating the documentation of the field `ttl`. + + +[2021-05-19] Version 6.59.0 +--------------------------- +**Events** +- add query param to return types filtered by Schema Id +- Add query param to return sinks filtered by status +- Add query param to return sinks used/not used by a subscription + +**Messaging** +- Add fetch and delete instance endpoints to us_app_to_person api **(breaking change)** +- Remove delete list endpoint from us_app_to_person api **(breaking change)** +- Update read list endpoint to return a list of us_app_to_person compliance objects **(breaking change)** +- Add `sid` field to Preregistered US App To Person response + +**Supersim** +- Mark `unique_name` in Sim, Fleet, NAP resources as not PII + +**Video** +- [Composer] GA maturity level + + +[2021-05-05] Version 6.58.0 +--------------------------- +**Api** +- Corrected the data types for feedback summary fields **(breaking change)** +- Update the conference participant create `from` and `to` param to be endpoint type for supporting client identifier and sip address + +**Bulkexports** +- promoting API maturity to GA + +**Events** +- Add endpoint to update description in sink +- Remove beta-feature account flag + +**Messaging** +- Update `status` field in us_app_to_person api to `campaign_status` **(breaking change)** + +**Verify** +- Improve documentation regarding `push` factor and include extra information about `totp` factor. + + +[2021-04-21] Version 6.57.0 +--------------------------- +**Api** +- Revert Update the conference participant create `from` and `to` param to be endpoint type for supporting client identifier and sip address +- Update the conference participant create `from` and `to` param to be endpoint type for supporting client identifier and sip address + +**Bulkexports** +- moving enum to doc root for auto generating documentation +- adding status enum and default output properties + +**Events** +- Change schema_versions prop and key to versions **(breaking change)** + +**Messaging** +- Add `use_inbound_webhook_on_number` field in Service API for fetch, create, update, read + +**Taskrouter** +- Add `If-Match` Header based on ETag for Task Delete + +**Verify** +- Add `AuthPayload` parameter to support verifying a `Challenge` upon creation. This is only supported for `totp` factors. +- Add support to resend the notifications of a `Challenge`. This is only supported for `push` factors. + +**Twiml** +- Add Polly Neural voices. + + +[2021-04-07] Version 6.56.0 +--------------------------- +**Api** +- Added `announcement` event to conference status callback events +- Removed optional property `time_limit` in the call create request. **(breaking change)** + +**Messaging** +- Add rate_limits field to Messaging Services US App To Person API +- Add usecase field in Service API for fetch, create, update, read +- Add us app to person api and us app to person usecase api as dependents in service +- Add us_app_to_person_registered field in service api for fetch, read, create, update +- Add us app to person api +- Add us app to person usecase api +- Add A2P external campaign api +- Add Usecases API + +**Supersim** +- Add Create endpoint to Sims resource + +**Verify** +- The `Binding` field is now returned when creating a `Factor`. This value won't be returned for other endpoints. + +**Video** +- [Rooms] max_concurrent_published_tracks has got GA maturity + +**Twiml** +- Add `announcement` event to `statusCallbackEvent` for ``. + + +[2021-03-24] Version 6.55.0 +--------------------------- +**Api** +- Added optional parameter `CallToken` for create calls api +- Add optional property `time_limit` in the call create request. + +**Bulkexports** +- adding two new fields with job api queue_position and estimated_completion_time + +**Events** +- Add new endpoints to manage subscribed_events in subscriptions + +**Numbers** +- Remove feature flags for RegulatoryCompliance endpoints + +**Supersim** +- Add SmsCommands resource +- Add fields `SmsCommandsUrl`, `SmsCommandsMethod` and `SmsCommandsEnabled` to a Fleet resource + +**Taskrouter** +- Add `If-Match` Header based on ETag for Task Update +- Add `ETag` as Response Headers to Tasks and Reservations + +**Video** +- Recording rule beta flag **(breaking change)** +- [Rooms] Add RecordingRules param to Rooms + + +[2021-03-15] Version 6.54.0 +--------------------------- +**Library - Chore** +- [PR #563](https://github.com/twilio/twilio-python/pull/563): Add support for python 3.9. Thanks to [@tim-schilling](https://github.com/tim-schilling)! + +**Events** +- Set maturity to beta + +**Messaging** +- Adjust A2P brand registration status enum **(breaking change)** + +**Studio** +- Remove internal safeguards for Studio V2 API usage now that it's GA + +**Verify** +- Add support for creating and verifying totp factors. Support for totp factors is behind the `api.verify.totp` beta feature. + +**Twiml** +- Add support for `` noun + + +[2021-02-24] Version 6.53.0 +--------------------------- +**Library - Chore** +- [PR #561](https://github.com/twilio/twilio-python/pull/561): removed file exec to get version. Thanks to [@shwetha-manvinkurke](https://github.com/shwetha-manvinkurke)! + +**Events** +- Update description of types in the create sink resource + +**Messaging** +- Add WA template header and footer +- Remove A2P campaign and use cases API **(breaking change)** +- Add number_registration_status field to read and fetch campaign responses + +**Trusthub** +- Make all resources public + +**Verify** +- Verify List Attempts API endpoints added. + + +[2021-02-10] Version 6.52.0 +--------------------------- +**Library - Docs** +- [PR #553](https://github.com/twilio/twilio-python/pull/553): fix simple typo, ommited -> omitted. Thanks to [@timgates42](https://github.com/timgates42)! + +**Library - Fix** +- [PR #558](https://github.com/twilio/twilio-python/pull/558): shortcut syntax for new non-GA versions. Thanks to [@eshanholtz](https://github.com/eshanholtz)! + +**Api** +- Revert change that conference participant create `from` and `to` param to be endpoint type for supporting client identifier and sip address +- Update the conference participant create `from` and `to` param to be endpoint type for supporting client identifier and sip address + +**Events** +- Documentation should state that no fields are PII + +**Flex** +- Adding `notifications` and `markdown` to Flex Configuration + +**Messaging** +- Add A2P use cases API +- Add Brand Registrations API +- Add Campaigns API + +**Serverless** +- Add runtime field to Build response and as an optional parameter to the Build create endpoint. +- Add @twilio/runtime-handler dependency to Build response example. + +**Sync** +- Remove If-Match header for Document **(breaking change)** + +**Twiml** +- Add `refer_url` and `refer_method` to `Dial`. + + +[2021-01-27] Version 6.51.1 +--------------------------- +**Studio** +- Studio V2 API is now GA + +**Supersim** +- Allow updating `CommandsUrl` and `CommandsMethod` on a Fleet + +**Twiml** +- Add `status_callback` and `status_callback_method` to `Stream`. + + +[2021-01-13] Version 6.51.0 +--------------------------- +**Library - Docs** +- [PR #555](https://github.com/twilio/twilio-python/pull/555): Fixing documentation for list parameter types. Thanks to [@shwetha-manvinkurke](https://github.com/shwetha-manvinkurke)! + +**Library - Fix** +- [PR #552](https://github.com/twilio/twilio-python/pull/552): pin pyjwt dependency. Thanks to [@thinkingserious](https://github.com/thinkingserious)! + +**Api** +- Add 'Electric Imp v1 Usage' to usage categories + +**Conversations** +- Changed `last_read_message_index` type in Participant's resource **(breaking change)** + +**Insights** +- Added `created_time` to call summary. + +**Sync** +- Remove HideExpired query parameter for filtering Sync Documents with expired **(breaking change)** + +**Video** +- [Rooms] Expose maxConcurrentPublishedTracks property in Room resource + + +[2020-12-16] Version 6.50.1 +--------------------------- +**Api** +- Updated `call_event` default_output_properties to request and response. + +**Conversations** +- Added `last_read_message_index` and `last_read_timestamp` to Participant's resource update operation +- Added `is_notifiable` and `is_online` to User's resource +- Added `reachability_enabled` parameters to update method for Conversation Service Configuration resource + +**Messaging** +- Added WA template quick reply, URL, and phone number buttons + +**Twiml** +- Add `sequential` to `Dial`. + + +[2020-12-08] Version 6.50.0 +--------------------------- +**Api** +- Added optional `RecordingTrack` parameter for create calls, create participants, and create call recordings +- Removed deprecated Programmable Chat usage record categories **(breaking change)** + +**Twiml** +- Add `recordingTrack` to `Dial`. + + +[2020-12-02] Version 6.49.0 +--------------------------- +**Library - Feature** +- [PR #546](https://github.com/twilio/twilio-python/pull/546): Regional twr header in the access token. Thanks to [@charliesantos](https://github.com/charliesantos)! + +**Api** +- Remove `RecordingTrack` parameter for create calls, create participants, and create call recordings **(breaking change)** +- Added `RecordingTrack` parameter for create calls and create call recordings +- Add optional property `recording_track` in the participant create request + +**Lookups** +- Changed `caller_name` and `carrier` properties type to object **(breaking change)** + +**Trunking** +- Added dual channel recording options for Trunks. + +**Twiml** +- Add `jitterBufferSize` and `participantLabel` to `Conference`. + + +[2020-11-18] Version 6.48.0 +--------------------------- +**Api** +- Add new call events resource - GET /2010-04-01/Accounts/{account_sid}/Calls/{call_sid}/Events.json + +**Conversations** +- Fixed default response property issue for Service Notifications Configuration + +**Insights** +- Removing call_sid from participant summary. **(breaking change)** + +**Serverless** +- Allow Service unique name to be used in path (in place of SID) in Service update request + +**Sync** +- Added HideExpired query parameter for filtering Sync Documents with expired + +**Verify** +- Challenge `Details` and `HiddenDetails` properties are now marked as `PII` +- Challenge `expiration_date` attribute updated to set a default value of five (5) minutes and to allow max dates of one (1) hour after creation. +- Entity `identity` attribute updated to allow values between 8 and 64 characters. +- Verify Service frinedly_name attribute updated from 64 max lenght to 30 characters. + + +[2020-11-05] Version 6.47.0 +--------------------------- +**Library - Docs** +- [PR #544](https://github.com/twilio/twilio-python/pull/544): add debug logging example. Thanks to [@thinkingserious](https://github.com/thinkingserious)! + +**Api** +- Added `verify-push` to `usage_record` API + +**Bulkexports** +- When creating a custom export the StartDay, EndDay, and FriendlyName fields were required but this was not reflected in the API documentation. The API itself failed the request without these fields. **(breaking change)** +- Added property descriptions for Custom Export create method +- Clarified WebhookUrl and WebhookMethod must be provided together for Custom Export + +**Insights** +- Added video room and participant summary apis. + +**Ip_messaging** +- Create separate definition for ip-messaging +- Restore v2 endpoints for ip-messaging + +**Verify** +- Verify Push madurity were updated from `preview` to `beta` +- `twilio_sandbox_mode` header was removed from Verify Push resources **(breaking change)** + +**Video** +- [Rooms] Add Recording Rules API + + +[2020-10-14] Version 6.46.0 +--------------------------- +**Library - Docs** +- [PR #542](https://github.com/twilio/twilio-python/pull/542): add path limit error for windows. Thanks to [@hack3r-0m](https://github.com/hack3r-0m)! + +**Ai** +- Add `Annotation Project` and `Annotation Task` endpoints +- Add `Primitives` endpoints +- Add `meta.total` to the search endpoint + +**Conversations** +- Mutable Conversation Unique Names + +**Insights** +- Added `trust` to summary. + +**Preview** +- Simplified `Channels` resource. The path is now `/BrandedChannels/branded_channel_sid/Channels` **(breaking change)** + +**Verify** +- Changed parameters (`config` and `binding`) to use dot notation instead of JSON string (e.i. Before: `binding={"alg":"ES256", "public_key": "xxx..."}`, Now: `Binding.Alg="ES256"`, `Binding.PublicKey="xxx..."`). **(breaking change)** +- Changed parameters (`details` and `hidden_details`) to use dot notation instead of JSON string (e.i. Before: `details={"message":"Test message", "fields": "[{\"label\": \"Action 1\", \"value\":\"value 1\"}]"}`, Now: `details.Message="Test message"`, `Details.Fields=["{\"label\": \"Action 1\", \"value\":\"value 1\"}"]`). **(breaking change)** +- Removed `notify_service_sid` from `push` service configuration object. Add `Push.IncludeDate`, `Push.ApnCredentialSid` and `Push.FcmCredentialSid` service configuration parameters. **(breaking change)** + + +[2020-09-28] Version 6.45.4 +--------------------------- +**Library - Docs** +- [PR #541](https://github.com/twilio/twilio-python/pull/541): Fix pip download link. Thanks to [@swarnava](https://github.com/swarnava)! + +**Api** +- Add optional property `call_reason` in the participant create request +- Make sip-domain-service endpoints available in stage-au1 and prod-au1 + +**Messaging** +- Removed beta feature gate from WhatsApp Templates API + +**Serverless** +- Add Build Status endpoint + +**Video** +- [Rooms] Add new room type "go" for WebRTC Go + + +[2020-09-21] Version 6.45.3 +--------------------------- +**Library - Fix** +- [PR #540](https://github.com/twilio/twilio-python/pull/540): allow API redirect responses. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Accounts** +- Add Auth Token rotation API + +**Conversations** +- Change resource path for Webhook Configuration + +**Events** +- Schemas API get all Schemas names and versions + + +[2020-09-16] Version 6.45.2 +--------------------------- +**Conversations** +- Expose Configuration and Service Configuration resources +- Add Unique Name support for Conversations +- Add Services Push Notification resource +- Add Service scoped Conversation resources +- Support Identity in Users resource endpoint + +**Messaging** +- GA Deactivation List API +- Add domain cert API's(fetch, update, create) for link tracker + +**Numbers** +- Add API endpoint for Supporting Document deletion + +**Proxy** +- Updated usage of FailOnParticipantConflict param to apply only to accounts with ProxyAllowParticipantConflict account flag + +**Supersim** +- Add `AccountSid` parameter to Sim resource update request +- Add `ready` status as an available status for a Sim resource + + +[2020-09-02] Version 6.45.1 +--------------------------- +**Library - Docs** +- [PR #538](https://github.com/twilio/twilio-python/pull/538): convert markdown links to rst formatted links. Thanks to [@thinkingserious](https://github.com/thinkingserious)! + +**Ai** +- Initial release + +**Bulkexports** +- removing public beta feature flag from BulkExports Jobs API + +**Messaging** +- Add Deactivation List API +- Added page token parameter for fetch in WhatsApp Templates API + +**Numbers** +- Add API endpoint for End User deletion + +**Routes** +- Add Resource Route Configurations API +- Add Route Configurations API +- Initial Release + +**Trunking** +- Added `transfer_mode` property on Trunks. + + +[2020-08-19] Version 6.45.0 +--------------------------- +**Library - Chore** +- [PR #536](https://github.com/twilio/twilio-python/pull/536): update GitHub branch references to use HEAD. Thanks to [@thinkingserious](https://github.com/thinkingserious)! + +**Conversations** +- Allow Identity addition to Participants + +**Events** +- Sinks API Get all Sinks + +**Proxy** +- Clarified usage of FailOnParticipantConflict param as experimental +- Add FailOnParticipantConflict param to Proxy Session create and Proxy Participant create + +**Supersim** +- Add fleet, network, and isoCountryCode to the UsageRecords resource +- Change sort order of UsageRecords from ascending to descending with respect to start time field, records are now returned newest to oldest + +**Wireless** +- Removed `Start` and `End` parameters from the Data Sessions list endpoint. **(breaking change)** + + +[2020-08-05] Version 6.44.2 +--------------------------- +**Messaging** +- Add rejection reason support to WhatsApp API +- Removed status parameter for create and update in WhatsApp Templates API + +**Proxy** +- Add FailOnParticipantConflict param to Proxy Session update + +**Verify** +- Add `CustomFriendlyName` optional parameter on Verification creation. +- Changes in `Challenge` resource to update documentation of both `details` and `hidden_details` properties. + + +[2020-07-22] Version 6.44.1 +--------------------------- +**Api** +- Add optional Click Tracking and Scheduling parameters to Create action of Message resource + +**Supersim** +- Add callback_url and callback_method parameters to Sim resource update request + + +[2020-07-08] Version 6.44.0 +--------------------------- +**Library - Feature** +- [PR #528](https://github.com/twilio/twilio-python/pull/528): include API response headers in 'Last Response'. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Conversations** +- Allow Address updates for Participants +- Message delivery receipts + +**Events** +- Add account_sid to subscription and subscribed_events resources + +**Flex** +- Changed `wfm_integrations` Flex Configuration key to private **(breaking change)** + +**Messaging** +- Add error states to WhatsApp Sender status with failed reason **(breaking change)** +- Delete WhatsApp Template API +- Update WhatsApp Template API +- Add WhatsApp Template Get Api (fetch and read) + +**Numbers** +- Add `valid_until` in the Bundles resource +- Add API for Bundle deletion + +**Verify** +- Removed support for `sms`, `totp` and `app-push` factor types in Verify push **(breaking change)** + + +[2020-06-24] Version 6.43.0 +--------------------------- +**Api** +- Added optional `JitterBufferSize` parameter for creating conference participant +- Added optional `label` property for conference participants +- Added optional parameter `caller_id` for creating conference participant endpoint. + +**Autopilot** +- Remove Export resource from Autopilot Assistant + +**Conversations** +- Expose Conversation timers + +**Monitor** +- Update start/end date filter params to support date-or-time format **(breaking change)** + +**Numbers** +- Add `provisionally-approved` as a Supporting Document status + +**Preview** +- Removed `Authy` resources. **(breaking change)** + +**Supersim** +- Add ready state to the allowed transitions in the sim update call behind the feature flag supersim.ready-state.v1 + +**Verify** +- Webhook resources added to Verify services and put behind the `api.verify.push` beta feature + +**Twiml** +- Add more supported locales for the `Gather` verb. + + +[2020-06-10] Version 6.42.0 +--------------------------- +**Library - Docs** +- [PR #525](https://github.com/twilio/twilio-python/pull/525): link to handling exceptions. Thanks to [@thinkingserious](https://github.com/thinkingserious)! +- [PR #524](https://github.com/twilio/twilio-python/pull/524): link to custom HTTP client instructions. Thanks to [@thinkingserious](https://github.com/thinkingserious)! + +**Library - Fix** +- [PR #523](https://github.com/twilio/twilio-python/pull/523): drop the page limit calculation and correct the page limit stop condition. Thanks to [@childish-sambino](https://github.com/childish-sambino)! +- [PR #522](https://github.com/twilio/twilio-python/pull/522): drop passing a page limit when listing/streaming resources. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Added `pstnconnectivity` to `usage_record` API + +**Autopilot** +- Add dialogue_sid param to Query list resource + +**Notify** +- delivery_callback_url and delivery_callback_enabled added + +**Numbers** +- Add `provisionally-approved` as a Bundle status + +**Preview** +- `BrandsInformation` endpoint now returns a single `BrandsInformation` +- Deleted phone number required field in the brand phone number endpoint from `kyc-api` +- Removed insights `preview API` from API Definitions **(breaking change)** +- Added `BrandsInformation` endpoint to query brands information stored in KYC + +**Supersim** +- Require a Network Access Profile when creating a Fleet **(breaking change)** + + +[2020-05-27] Version 6.41.0 +--------------------------- +**Api** +- Added `reason_conference_ended` and `call_sid_ending_conference` to Conference read/fetch/update +- Fixed some examples to use the correct "TK" SID prefix for Trunk resources. + +**Authy** +- Renamed `twilio_authy_sandbox_mode` headers to `twilio_sandbox_mode` **(breaking change)** +- Renamed `Twilio-Authy-*` headers to `Twilio-Veriry-*` **(breaking change)** + +**Flex** +- Adding `flex_service_instance_sid` to Flex Configuration + +**Preview** +- Removed insights preview API from API Definitions **(breaking change)** +- Added `Channels` endpoint to brand a phone number for BrandedCalls + +**Serverless** +- Add Build Sid to Log results + +**Supersim** +- Add Network Access Profile resource Networks subresource +- Allow specifying a Data Limit on Fleets + +**Trunking** +- Fixed some examples to use the correct "TK" SID prefix for Trunk resources. + + +[2020-05-13] Version 6.40.0 +--------------------------- +**Library - Feature** +- [PR #520](https://github.com/twilio/twilio-python/pull/520): add regional and edge support. Thanks to [@eshanholtz](https://github.com/eshanholtz)! + +**Api** +- Add optional `emergency_caller_sid` parameter to SIP Domain +- Updated `call_reason` optional property to be treated as PII +- Added optional BYOC Trunk Sid property to Sip Domain API resource + +**Autopilot** +- Add Restore resource to Autopilot Assistant + +**Contacts** +- Added contacts Create API definition + +**Events** +- Subscriptions API initial release + +**Numbers** +- Add Evaluations API + +**Supersim** +- Allow filtering the Fleets resource by Network Access Profile +- Allow assigning a Network Access Profile when creating and updating a Fleet +- Add Network Access Profiles resource + +**Verify** +- Add `CustomCode` optional parameter on Verification creation. +- Add delete action on Service resource. + +**Voice** +- Added endpoints for BYOC trunks, SIP connection policies and source IP mappings + + +[2020-04-29] Version 6.39.0 +--------------------------- +**Library - Feature** +- [PR #517](https://github.com/twilio/twilio-python/pull/517): add details to TwilioRestException. Thanks to [@ashish-s](https://github.com/ashish-s)! + +**Preview** +- Added `Dispatch` version to `preview` + +**Studio** +- Reroute Create Execution for V2 to the V2 downstream + +**Supersim** +- Add Networks resource + + +[2020-04-15] Version 6.38.1 +--------------------------- +**Library - Chore** +- [PR #513](https://github.com/twilio/twilio-python/pull/513): remove S3 URLs from test data. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Updated description for property `call_reason` in the call create request + +**Contacts** +- Added Read, Delete All, and Delete by SID docs +- Initial Release + +**Studio** +- Rename `flow_valid` to `flow_validate` +- Removed `errors` and `warnings` from flows error response and added new property named `details` +- Add Update Execution endpoints to v1 and v2 to end execution via API +- Add new `warnings` attribute v2 flow POST api + +**Twiml** +- Add enhanced attribute to use with `speech_model` for the `Gather` verb + + [2020-04-01] Version 6.38.0 --------------------------- **Api** @@ -238,6 +3357,7 @@ Here you can see the full list of changes between each twilio-python release. **Api** - Make `persistent_action` parameter public - Add `twiml` optional private parameter for call create +- Update the call `price` property type to be string **(breaking change)** **Autopilot** - Add Export resource to Autopilot Assistant. 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 2b5d1f0836..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,60 +15,114 @@ 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: + +```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. - python setup.py install +## 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. -You may need to run the above commands with `sudo`. +API examples [here](https://github.com/twilio/twilio-python/blob/main/examples/public_oauth.py) -## Getting Started +Organisation API examples [here](https://github.com/twilio/twilio-python/blob/main/examples/organization_api.py) -Getting started with the Twilio API couldn't be easier. Create a -`Client` and you're ready to go. +## Use the helper library ### API Credentials -The `Twilio` needs your Twilio credentials. You can either pass these -directly to the constructor (see the code below) or via environment variables. +The `Twilio` client needs your Twilio credentials. You can either pass these directly to the constructor (see the code below) or via environment variables. + +Authenticating with Account SID and Auth Token: ```python from twilio.rest import Client -account = "ACXXXXXXXXXXXXXXXXX" -token = "YYYYYYYYYYYYYYYYYY" -client = Client(account, token) +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) ``` -Alternately, a `Client` constructor without these parameters will +Authenticating with API Key and API Secret: + +```python +from twilio.rest import Client + +api_key = "XXXXXXXXXXXXXXXXX" +api_secret = "YYYYYYYYYYYYYYYYYY" +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +client = Client(api_key, api_secret, account_sid) +``` + +Alternatively, a `Client` constructor without these parameters will look for `TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN` variables inside the current environment. @@ -76,20 +130,45 @@ We suggest storing your credentials as environment variables. Why? You'll never have to worry about committing your credentials and accidentally posting them somewhere public. +```python +from twilio.rest import Client +client = Client() +``` + +### Specify Region and/or Edge + +To take advantage of Twilio's [Global Infrastructure](https://www.twilio.com/docs/global-infrastructure), specify the target Region and Edge for the client: + +> **Note:** When specifying a `region` parameter for a helper library client, be sure to also specify the `edge` parameter. For backward compatibility purposes, specifying a `region` without specifying an `edge` will result in requests being routed to US1. ```python from twilio.rest import Client + +client = Client(region='au1', edge='sydney') +``` + +A `Client` constructor without these parameters will also look for `TWILIO_REGION` and `TWILIO_EDGE` variables inside the current environment. + +Alternatively, you may specify the edge and/or region after constructing the Twilio client: + +```python +from twilio.rest import Client + client = Client() +client.region = 'au1' +client.edge = 'sydney' ``` +This will result in the `hostname` transforming from `api.twilio.com` to `api.sydney.au1.twilio.com`. + ### Make a Call ```python from twilio.rest import Client -account = "ACXXXXXXXXXXXXXXXXX" -token = "YYYYYYYYYYYYYYYYYY" -client = Client(account, token) +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) call = client.calls.create(to="9991231234", from_="9991231234", @@ -97,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_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) + +call = client.calls.get("CA42ed11f93dc08b952027ffbc406d0868") +print(call.to) +``` + +### Iterate through records + +The library automatically handles paging for you. Collections, such as `calls` and `messages`, have `list` and `stream` methods that page under the hood. With both `list` and `stream`, you can specify the number of records you want to receive (`limit`) and the maximum size you want each page fetch to be (`page_size`). The library will then handle the task for you. + +`list` eagerly fetches all records and returns them as a list, whereas `stream` returns an iterator and lazily retrieves pages of records as you iterate over the collection. You can also page manually using the `page` method. + +`page_size` as a parameter is used to tell how many records should we get in every page and `limit` parameter is used to limit the max number of records we want to fetch. + +#### Use the `list` method + +```python +from twilio.rest import Client + +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) + +for sms in client.messages.list(): + print(sms.to) +``` + +```python +client.messages.list(limit=20, page_size=20) +``` +This will make 1 call that will fetch 20 records from backend service. + +```python +client.messages.list(limit=20, page_size=10) +``` +This will make 2 calls that will fetch 10 records each from backend service. ```python +client.messages.list(limit=20, page_size=100) +``` +This will make 1 call which will fetch 100 records but user will get only 20 records. + +### Asynchronous API Requests + +By default, the Twilio Client will make synchronous requests to the Twilio API. To allow for asynchronous, non-blocking requests, we've included an optional asynchronous HTTP client. When used with the Client and the accompanying `*_async` methods, requests made to the Twilio API will be performed asynchronously. + +```python +from twilio.http.async_http_client import AsyncTwilioHttpClient from twilio.rest import Client -account = "ACXXXXXXXXXXXXXXXXX" -token = "YYYYYYYYYYYYYYYYYY" -client = Client(account, token) +async def main(): + account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + auth_token = "your_auth_token" + http_client = AsyncTwilioHttpClient() + client = Client(account_sid, auth_token, http_client=http_client) + + message = await client.messages.create_async(to="+12316851234", from_="+15555555555", + body="Hello there!") + +asyncio.run(main()) +``` + +### Enable Debug Logging -message = client.messages.create(to="+12316851234", from_="+15555555555", - body="Hello there!") +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", @@ -146,6 +305,10 @@ print(str(r)) Welcome to twilio! ``` +### Other advanced examples + +- [Learn how to create your own custom HTTP client](./advanced-examples/custom-http-client.md) + ### Docker Image The `Dockerfile` present in this repository and its respective `twilio/twilio-python` Docker image are currently used by Twilio for testing purposes only. 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..3e1b634387 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -15,15 +15,15 @@ # import os import sys -sys.path.insert(0, os.path.abspath('..')) -from twilio import __version__ +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 +41,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 +77,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 +85,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 +93,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 +104,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 +126,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 +141,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 +155,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 +164,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 +194,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 +202,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..7f2e42c58b 100644 --- a/examples/client_validation.py +++ b/examples/client_validation.py @@ -6,15 +6,15 @@ 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 +28,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..124531fc46 --- /dev/null +++ b/examples/public_oauth.py @@ -0,0 +1,28 @@ +import os + +from twilio.rest import Client +from twilio.credential.client_credential_provider import ClientCredentialProvider + +ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID") +MESSAGE_SID = os.environ.get("TWILIO_MESSAGE_SID") + +CLIENT_ID = os.environ.get("TWILIO_CLIENT_ID") +CLIENT_SECRET = os.environ.get("TWILIO_CLIENT_SECRET") + + +def example(): + """ + An example usage of message resource. + """ + client = Client( + account_sid=ACCOUNT_SID, + credential_provider=ClientCredentialProvider(CLIENT_ID, CLIENT_SECRET), + ) + + msg = client.messages(MESSAGE_SID).fetch() + + print(msg) + + +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..09672cd205 --- 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.10.9", 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..81db67683b 100644 --- a/tests/holodeck.py +++ b/tests/holodeck.py @@ -1,22 +1,21 @@ from twilio.base.exceptions import TwilioRestException -from twilio.http import HttpClient +from twilio.http import HttpClient, AsyncHttpClient from twilio.http.request import Request import platform from twilio import __version__ class Hologram(object): - def __init__(self, request, response): self.request = request self.response = response class Holodeck(HttpClient): - def __init__(self): self._holograms = [] self._requests = [] + self.is_async = False def mock(self, response, request=None): request = request or Request() @@ -28,16 +27,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 +50,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 +80,94 @@ 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) + +class AsyncHolodeck(AsyncHttpClient): + """Async version of Holodeck for async testing""" + + def __init__(self): + # Don't call super().__init__() to avoid logger requirement + self._holograms = [] + self._requests = [] + self.is_async = True + + def mock(self, response, request=None): + request = request or Request() + self._holograms.append(Hologram(request, response)) + + @property + def requests(self): + return self._requests + + def add_standard_headers(self, request): + standard_headers = { + "User-Agent": "twilio-python/{} ({} {}) Python/{}".format( + __version__, + platform.system(), + platform.machine(), + platform.python_version(), + ), + "X-Twilio-Client": "python-{}".format(__version__), + "Accept": "application/json", + "Accept-Charset": "utf-8", + } + + if request.method == "POST" and "Content-Type" not in standard_headers: + standard_headers["Content-Type"] = "application/x-www-form-urlencoded" + + standard_headers.update(request.headers) + request.headers = standard_headers + return request + + def assert_has_request(self, request): + for req in self.requests: + if req == request or req == self.add_standard_headers(request): + return + + message = "\nHolodeck never received a request matching: \n + {}\n".format( + request + ) + if self._requests: + message += "Requests received:\n" + message += "\n".join(" * {}".format(r) for r in self.requests) + else: + message += "No Requests received" + + raise AssertionError(message) + + async def request( + self, + method, + url, + params=None, + data=None, + headers=None, + auth=None, + timeout=None, + allow_redirects=False, + ): + """Async request method""" + request = Request(method, url, auth, params, data, headers) + + self._requests.append(request) + + for hologram in self._holograms: + if hologram.request == request: + return hologram.response + + message = "\nHolodeck has no hologram for: {}\n".format(request) + if self._holograms: + message += "Holograms loaded:\n" + message += "\n".join(" - {}".format(h.request) for h in self._holograms) + else: + message += "No Holograms loaded" + + raise TwilioRestException(404, url, message, method=method) diff --git a/tests/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 1ea5bdb6c3..0000000000 --- a/tests/integration/api/v2010/account/conference/test_participant.py +++ /dev/null @@ -1,508 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.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", - "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", - "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", - "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", - "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", - "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", - "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", - "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", - "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_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_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", - "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", - "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", - "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", - "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", - "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", - "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 0336a1582d..0000000000 --- a/tests/integration/api/v2010/account/sip/test_domain.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 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 - } - ], - "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 - } - ''' - )) - - 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 - } - ''' - )) - - 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 - } - ''' - )) - - 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 5adcaf97a4..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": "TRdeadbeefdeadbeefdeadbeefdeadbeef", - "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": "TRdeadbeefdeadbeefdeadbeefdeadbeef", - "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": "TRdeadbeefdeadbeefdeadbeefdeadbeef", - "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": "TRdeadbeefdeadbeefdeadbeefdeadbeef", - "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": "TRdeadbeefdeadbeefdeadbeefdeadbeef", - "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 76bdffc1a5..0000000000 --- a/tests/integration/api/v2010/account/test_conference.py +++ /dev/null @@ -1,416 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.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" - } - ''' - )) - - 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" - } - ''' - )) - - 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" - } - ''' - )) - - 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" - } - ''' - )) - - 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" - }, - { - "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" - }, - { - "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" - } - ], - "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" - }, - { - "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" - }, - { - "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" - } - ], - "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" - }, - { - "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" - }, - { - "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" - } - ], - "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" - } - ''' - )) - - 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 e6560b98ed..0000000000 --- a/tests/integration/api/v2010/account/test_incoming_phone_number.py +++ /dev/null @@ -1,323 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.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": { - "mms": true, - "sms": false, - "voice": true - }, - "date_created": "Thu, 30 Jul 2015 23:19:04 +0000", - "date_updated": "Thu, 30 Jul 2015 23:19:04 +0000", - "emergency_status": "Inactive", - "emergency_address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "(808) 925-5327", - "identity_sid": "RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "origin": "origin", - "phone_number": "+18089255327", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_application_sid": "", - "sms_fallback_method": "POST", - "sms_fallback_url": "", - "sms_method": "POST", - "sms_url": "", - "status_callback": "", - "status_callback_method": "POST", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_application_sid": "", - "voice_caller_id_lookup": false, - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_url": null, - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - 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": { - "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" - } - ''' - )) - - 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" - } - ], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=2", - "next_page_uri": null, - "num_pages": 3, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 3, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=0", - "incoming_phone_numbers": [], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=2", - "next_page_uri": null, - "num_pages": 3, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 3, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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" - } - ''' - )) - - 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 34b18da84b..0000000000 --- a/tests/integration/api/v2010/account/test_outgoing_caller_id.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 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, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 21 Aug 2009 00:11:24 +0000", - "date_updated": "Fri, 21 Aug 2009 00:11:24 +0000", - "friendly_name": "(415) 867-5309", - "phone_number": "+141586753096", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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": "(415) 867-5309", - "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?Page=0&PageSize=50", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json?Page=0&PageSize=50", - "next_page_uri": null, - "num_pages": 1, - "outgoing_caller_ids": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 21 Aug 2009 00:11:24 +0000", - "date_updated": "Fri, 21 Aug 2009 00:11:24 +0000", - "friendly_name": "(415) 867-5309", - "phone_number": "+141586753096", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json?Page=0&PageSize=50", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json?Page=0&PageSize=50", - "next_page_uri": null, - "num_pages": 1, - "outgoing_caller_ids": [], - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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 4e1860c0cb..0000000000 --- a/tests/integration/api/v2010/account/test_token.py +++ /dev/null @@ -1,59 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.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, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 24 Jul 2015 18:43:58 +0000", - "date_updated": "Fri, 24 Jul 2015 18:43:58 +0000", - "ice_servers": [ - { - "url": "stun:global.stun:3478?transport=udp", - "urls": "stun:global.stun:3478?transport=udp" - }, - { - "credential": "5SR2x8mZK1lTFJW3NVgLGw6UM9C0dja4jI/Hdw3xr+w=", - "url": "turn:global.turn:3478?transport=udp", - "urls": "turn:global.turn:3478?transport=udp", - "username": "cda92e5006c7810494639fc466ecc80182cef8183fdf400f84c4126f3b59d0bb" - } - ], - "password": "5SR2x8mZK1lTFJW3NVgLGw6UM9C0dja4jI/Hdw3xr+w=", - "ttl": "86400", - "username": "cda92e5006c7810494639fc466ecc80182cef8183fdf400f84c4126f3b59d0bb" - } - ''' - )) - - 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 f466641115..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": 100 - } - ''' - )) - - 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/authy/__init__.py b/tests/integration/authy/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/authy/__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/authy/v1/__init__.py b/tests/integration/authy/v1/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/authy/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/authy/v1/service/__init__.py b/tests/integration/authy/v1/service/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/authy/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/authy/v1/service/entity/__init__.py b/tests/integration/authy/v1/service/entity/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/authy/v1/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/authy/v1/service/entity/factor/__init__.py b/tests/integration/authy/v1/service/entity/factor/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/authy/v1/service/entity/factor/__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/authy/v1/service/entity/factor/test_challenge.py b/tests/integration/authy/v1/service/entity/factor/test_challenge.py deleted file mode 100644 index 4569b749b1..0000000000 --- a/tests/integration/authy/v1/service/entity/factor/test_challenge.py +++ /dev/null @@ -1,339 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.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.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .challenges.create(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors/YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Challenges', - headers=headers, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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": "sms", - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Challenges/YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .challenges.create() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .challenges("sid").delete(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors/YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Challenges/sid', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .challenges("sid").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .challenges("sid").fetch(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors/YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Challenges/sid', - headers=headers, - )) - - def test_fetch_sid_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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": "sms", - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Challenges/YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .challenges("sid").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_latest_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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": "sms", - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Challenges/YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .challenges("sid").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .challenges.list(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors/YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/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://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Challenges?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Challenges?PageSize=50&Page=0", - "next_page_url": null, - "key": "challenges" - } - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .challenges.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "challenges": [ - { - "sid": "YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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": "sms", - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Challenges/YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Challenges?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Challenges?PageSize=50&Page=0", - "next_page_url": null, - "key": "challenges" - } - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .challenges.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .challenges("sid").update(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors/YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Challenges/sid', - headers=headers, - )) - - def test_verify_sid_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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": "sms", - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Challenges/YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .challenges("sid").update() - - self.assertIsNotNone(actual) - - def test_verify_latest_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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": "sms", - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Challenges/YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .challenges("sid").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/authy/v1/service/entity/test_factor.py b/tests/integration/authy/v1/service/entity/test_factor.py deleted file mode 100644 index 6e16316b46..0000000000 --- a/tests/integration/authy/v1/service/entity/test_factor.py +++ /dev/null @@ -1,295 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.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.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors.create(binding="binding", friendly_name="friendly_name", factor_type="app-push", config="config", twilio_authy_sandbox_mode="twilio_authy_sandbox_mode", authorization="authorization") - - values = { - 'Binding': "binding", - 'FriendlyName': "friendly_name", - 'FactorType': "app-push", - 'Config': "config", - } - - headers = { - 'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", - 'Authorization': "authorization", - } - self.holodeck.assert_has_request(Request( - 'post', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors', - headers=headers, - )) - self.holodeck.assert_has_request(Request( - 'post', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "challenges": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Challenges" - } - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors.create(binding="binding", friendly_name="friendly_name", factor_type="app-push", config="config") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors/YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors/YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "challenges": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Challenges" - } - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors.list(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/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://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors?PageSize=50&Page=0", - "next_page_url": null, - "key": "factors" - } - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "challenges": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Challenges" - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors?PageSize=50&Page=0", - "next_page_url": null, - "key": "factors" - } - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors/YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_verify_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "challenges": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Challenges" - } - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/authy/v1/service/test_entity.py b/tests/integration/authy/v1/service/test_entity.py deleted file mode 100644 index be12ad7882..0000000000 --- a/tests/integration/authy/v1/service/test_entity.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 EntityTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities.create(identity="identity", twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - values = {'Identity': "identity", } - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities', - headers=headers, - )) - self.holodeck.assert_has_request(Request( - 'post', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "YEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "ff483d1ff591898a9942916050d2ca3f", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f", - "links": { - "factors": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors" - } - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities.create(identity="identity") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity").delete(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity").fetch(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity', - headers=headers, - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "YEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "ff483d1ff591898a9942916050d2ca3f", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f", - "links": { - "factors": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors" - } - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities.list(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/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://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities?PageSize=50&Page=0", - "next_page_url": null, - "key": "entities" - } - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f", - "links": { - "factors": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors" - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities?PageSize=50&Page=0", - "next_page_url": null, - "key": "entities" - } - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/authy/v1/test_form.py b/tests/integration/authy/v1/test_form.py deleted file mode 100644 index 7f847df324..0000000000 --- a/tests/integration/authy/v1/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.authy.v1.forms("form-app-push").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://authy.twilio.com/v1/Forms/form-app-push', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "form_type": "form-sms", - "forms": { - "create_factor": {}, - "verify_factor": {}, - "create_challenge": {} - }, - "form_meta": {}, - "url": "https://authy.twilio.com/v1/Forms/form-sms" - } - ''' - )) - - actual = self.client.authy.v1.forms("form-app-push").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/authy/v1/test_service.py b/tests/integration/authy/v1/test_service.py deleted file mode 100644 index d8643b01bb..0000000000 --- a/tests/integration/authy/v1/test_service.py +++ /dev/null @@ -1,225 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.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.authy.v1.services.create(friendly_name="friendly_name", twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - values = {'FriendlyName': "friendly_name", } - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://authy.twilio.com/v1/Services', - headers=headers, - )) - self.holodeck.assert_has_request(Request( - 'post', - 'https://authy.twilio.com/v1/Services', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "configuration": {}, - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "entities": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities" - } - } - ''' - )) - - actual = self.client.authy.v1.services.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "configuration": {}, - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "entities": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities" - } - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services.list(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://authy.twilio.com/v1/Services', - headers=headers, - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "services": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://authy.twilio.com/v1/Services?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://authy.twilio.com/v1/Services?PageSize=50&Page=0", - "next_page_url": null, - "key": "services" - } - } - ''' - )) - - actual = self.client.authy.v1.services.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "services": [ - { - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "configuration": {}, - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "entities": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities" - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://authy.twilio.com/v1/Services?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://authy.twilio.com/v1/Services?PageSize=50&Page=0", - "next_page_url": null, - "key": "services" - } - } - ''' - )) - - actual = self.client.authy.v1.services.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(twilio_authy_sandbox_mode="twilio_authy_sandbox_mode") - - headers = {'Twilio-Authy-Sandbox-Mode': "twilio_authy_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://authy.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "configuration": {}, - "url": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "entities": "https://authy.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities" - } - } - ''' - )) - - actual = self.client.authy.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").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_export_assistant.py b/tests/integration/autopilot/v1/assistant/test_export_assistant.py deleted file mode 100644 index 724c2e908e..0000000000 --- a/tests/integration/autopilot/v1/assistant/test_export_assistant.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 ExportAssistantTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .export_assistant().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Export', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Export", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "status": "building", - "error_code": null, - "schema": {} - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .export_assistant().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 f035ace859..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&Language=language&PageSize=50&Page=0", - "page": 0, - "key": "queries", - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries?Status=status&ModelBuild=UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&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&Language=language&PageSize=50&Page=0", - "page": 0, - "key": "queries", - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries?Status=status&ModelBuild=UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&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 f571ac5577..0000000000 --- a/tests/integration/autopilot/v1/test_assistant.py +++ /dev/null @@ -1,264 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.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", - "export_assistant": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Export" - }, - "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", - "export_assistant": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Export" - }, - "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", - "export_assistant": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Export" - }, - "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", - "export_assistant": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Export" - }, - "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/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/test_message.py b/tests/integration/conversations/v1/conversation/test_message.py deleted file mode 100644 index e0d0e01992..0000000000 --- a/tests/integration/conversations/v1/conversation/test_message.py +++ /dev/null @@ -1,277 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.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, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - 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, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - 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, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - 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, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - 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, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "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, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "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, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - 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 7e6209ffd8..0000000000 --- a/tests/integration/conversations/v1/conversation/test_participant.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 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" - }, - "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, - "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" - }, - "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" - }, - "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" - }, - "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" - }, - "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, - "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 2ecd5f53cb..0000000000 --- a/tests/integration/conversations/v1/test_conversation.py +++ /dev/null @@ -1,207 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.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", - "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", - "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", - "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", - "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 9b429f2708..0000000000 --- a/tests/integration/flex_api/v1/test_configuration.py +++ /dev/null @@ -1,591 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.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", - "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\\"]}" - } - ], - "wfm_integrations": [ - { - "name": "teleopti", - "type": "flex_wfm", - "active": true, - "config": "{\\"rta_callback_url\\":\\"https://twilio.com\\",\\"rta_feed_enabled\\": true, \\"historical_feed_enabled\\": true}", - "logo": "logo1", - "author": "somebody1" - }, - { - "name": "teleopti-stage", - "type": "flex_wfm", - "active": false, - "config": "{\\"rta_callback_url\\":\\"https://twilio.com\\",\\"rta_feed_enabled\\": true, \\"historical_feed_enabled\\": true}" - } - ], - "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", - "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\\"]}" - } - ], - "wfm_integrations": [ - { - "name": "teleopti", - "type": "flex_wfm", - "active": true, - "config": "{\\"rta_callback_url\\":\\"https://twilio.com\\",\\"rta_feed_enabled\\": true, \\"historical_feed_enabled\\": true}", - "logo": "logo1", - "author": "somebody1" - }, - { - "name": "teleopti-stage", - "type": "flex_wfm", - "active": false, - "config": "{\\"rta_callback_url\\":\\"https://twilio.com\\",\\"rta_feed_enabled\\": true, \\"historical_feed_enabled\\": true}" - } - ], - "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", - "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\\"]}" - } - ], - "wfm_integrations": [ - { - "name": "teleopti", - "type": "flex_wfm", - "active": true, - "config": "{\\"rta_callback_url\\":\\"https://twilio.com\\",\\"rta_feed_enabled\\": true, \\"historical_feed_enabled\\": true}", - "logo": "logo1", - "author": "somebody1" - }, - { - "name": "teleopti-stage", - "type": "flex_wfm", - "active": false, - "config": "{\\"rta_callback_url\\":\\"https://twilio.com\\",\\"rta_feed_enabled\\": true, \\"historical_feed_enabled\\": true}" - } - ], - "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_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 268c6f4fd8..0000000000 --- a/tests/integration/numbers/v2/regulatory_compliance/test_bundle.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 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", - "date_created": "2019-07-30T22:29:24Z", - "date_updated": "2019-07-31T01:09:00Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "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": "draft", - "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": { - "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", - "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": { - "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", - "date_created": "2019-07-30T22:29:24Z", - "date_updated": "2019-07-31T01:09:00Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "item_assignments": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ItemAssignments" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(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/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_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_business.py b/tests/integration/preview/trusted_comms/test_business.py deleted file mode 100644 index 22ac39b2e4..0000000000 --- a/tests/integration/preview/trusted_comms/test_business.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 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": { - "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 16f1139762..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 c1a6e50a34..0000000000 --- a/tests/integration/serverless/v1/service/environment/test_log.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 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", - "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 926c810ed1..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 01219d5065..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 e457a3c2b5..0000000000 --- a/tests/integration/studio/v1/flow/test_execution.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 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) 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 5db247d70a..0000000000 --- a/tests/integration/studio/v2/flow/test_execution.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 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) 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 8f94fb3302..0000000000 --- a/tests/integration/studio/v2/test_flow.py +++ /dev/null @@ -1,230 +0,0 @@ -# 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": [], - "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": [], - "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, - "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": [], - "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 10bec316ad..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_valid.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_valid.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/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 8a66151bef..0000000000 --- a/tests/integration/supersim/v1/test_fleet.py +++ /dev/null @@ -1,191 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.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() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://supersim.twilio.com/v1/Fleets', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "data_enabled": true, - "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", - "sid": "HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://supersim.twilio.com/v1/Fleets/HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.supersim.v1.fleets.create() - - 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_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, - "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?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?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?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?PageSize=50&Page=0" - }, - "fleets": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "Pilot Fleet", - "data_enabled": true, - "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, - "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_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, - "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_sim.py b/tests/integration/supersim/v1/test_sim.py deleted file mode 100644 index bc18a61ad4..0000000000 --- a/tests/integration/supersim/v1/test_sim.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 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&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?Status=new&Fleet=HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Iccid=11111111111111111111&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.supersim.v1.sims.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/Sims?Status=new&Fleet=MyFleet&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?Status=new&Fleet=MyFleet&Iccid=11111111111111111111&PageSize=50&Page=0" - }, - "sims": [ - { - "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.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 bdac762272..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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "domain_name": "test.pstn.twilio.com", - "disaster_recovery_method": "POST", - "disaster_recovery_url": "http://disaster-recovery.com", - "friendly_name": "friendly_name", - "secure": false, - "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/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "origination_urls": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls", - "credential_lists": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists", - "ip_access_control_lists": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists", - "phone_numbers": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "domain_name": "test.pstn.twilio.com", - "disaster_recovery_method": "POST", - "disaster_recovery_url": "http://disaster-recovery.com", - "friendly_name": "friendly_name", - "secure": false, - "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/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "origination_urls": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls", - "credential_lists": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists", - "ip_access_control_lists": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists", - "phone_numbers": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks?PageSize=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": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "domain_name": "test.pstn.twilio.com", - "disaster_recovery_method": "POST", - "disaster_recovery_url": "http://disaster-recovery.com", - "friendly_name": "friendly_name", - "secure": false, - "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/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "origination_urls": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls", - "credential_lists": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists", - "ip_access_control_lists": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists", - "phone_numbers": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers" - } - } - ] - } - ''' - )) - - actual = self.client.trunking.v1.trunks.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks?PageSize=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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "domain_name": "test.pstn.twilio.com", - "disaster_recovery_method": "GET", - "disaster_recovery_url": "http://updated-recovery.com", - "friendly_name": "updated_name", - "secure": true, - "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/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "origination_urls": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls", - "credential_lists": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists", - "ip_access_control_lists": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists", - "phone_numbers": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/trunking/v1/trunk/__init__.py b/tests/integration/trunking/v1/trunk/__init__.py deleted file mode 100644 index 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 627edb5dd5..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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialLists/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialLists/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists.create(credential_list_sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'CredentialListSid': "CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialLists', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists.create(credential_list_sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialLists', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credential_lists": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credential_lists": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists?PageSize=50&Page=0", - "next_page_url": null, - "key": "credential_lists" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/trunking/v1/trunk/test_ip_access_control_list.py b/tests/integration/trunking/v1/trunk/test_ip_access_control_list.py deleted file mode 100644 index 9ae80d8b37..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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAccessControlLists/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2018-05-02T17:29:34Z", - "date_updated": "2018-05-02T17:29:34Z", - "friendly_name": "friendly_name", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAccessControlLists/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists.create(ip_access_control_list_sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'IpAccessControlListSid': "ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAccessControlLists', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2018-04-30T20:59:06Z", - "date_updated": "2018-04-30T20:59:06Z", - "friendly_name": "friendly_name", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists.create(ip_access_control_list_sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAccessControlLists', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "ip_access_control_lists": [], - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists?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/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "ip_access_control_lists": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2018-05-02T17:29:34Z", - "date_updated": "2018-05-02T17:29:34Z", - "friendly_name": "friendly_name", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/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/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/trunking/v1/trunk/test_origination_url.py b/tests/integration/trunking/v1/trunk/test_origination_url.py deleted file mode 100644 index fa2bc62448..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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls("OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OriginationUrls/OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "weight": 1, - "date_updated": "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": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls("OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OriginationUrls/OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls.create(weight=1, priority=1, enabled=True, friendly_name="friendly_name", sip_url="https://example.com") - - values = { - 'Weight': 1, - 'Priority': 1, - 'Enabled': True, - 'FriendlyName': "friendly_name", - 'SipUrl': "https://example.com", - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OriginationUrls', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "weight": 1, - "date_updated": "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": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls.create(weight=1, priority=1, enabled=True, friendly_name="friendly_name", sip_url="https://example.com") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OriginationUrls', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls?PageSize=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/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/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": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls?PageSize=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/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls?PageSize=50&Page=0" - }, - "origination_urls": [] - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls("OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OriginationUrls/OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "weight": 2, - "date_updated": "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": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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 3cf47ecb86..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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2010-12-10T17:27:34Z", - "date_updated": "2015-10-09T11:36:32Z", - "friendly_name": "(415) 867-5309", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "phone_number": "+14158675309", - "api_version": "2010-04-01", - "voice_caller_id_lookup": null, - "voice_url": "", - "voice_method": "POST", - "voice_fallback_url": null, - "voice_fallback_method": null, - "status_callback": "", - "status_callback_method": "POST", - "voice_application_sid": null, - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_url": "", - "sms_method": "POST", - "sms_fallback_url": "", - "sms_fallback_method": "POST", - "sms_application_sid": "", - "address_requirements": "none", - "beta": false, - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "capabilities": { - "voice": true, - "sms": true, - "mms": true - }, - "links": { - "phone_number": "https://api.twilio.com/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.create(phone_number_sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'PhoneNumberSid': "PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2010-12-10T17:27:34Z", - "date_updated": "2015-10-09T11:36:32Z", - "friendly_name": "(415) 867-5309", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "phone_number": "+14158675309", - "api_version": "2010-04-01", - "voice_caller_id_lookup": null, - "voice_url": "", - "voice_method": "POST", - "voice_fallback_url": null, - "voice_fallback_method": null, - "status_callback": "", - "status_callback_method": "POST", - "voice_application_sid": null, - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_url": "", - "sms_method": "POST", - "sms_fallback_url": "", - "sms_fallback_method": "POST", - "sms_application_sid": "", - "address_requirements": "none", - "beta": false, - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "capabilities": { - "voice": true, - "sms": true, - "mms": true - }, - "links": { - "phone_number": "https://api.twilio.com/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.create(phone_number_sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers?PageSize=1&Page=0", - "key": "phone_numbers", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers?PageSize=1&Page=0" - }, - "phone_numbers": [ - { - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2010-12-10T17:27:34Z", - "date_updated": "2015-10-09T11:36:32Z", - "friendly_name": "(415) 867-5309", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "phone_number": "+14158675309", - "api_version": "2010-04-01", - "voice_caller_id_lookup": null, - "voice_url": "", - "voice_method": "POST", - "voice_fallback_url": null, - "voice_fallback_method": null, - "status_callback": "", - "status_callback_method": "POST", - "voice_application_sid": null, - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_url": "", - "sms_method": "POST", - "sms_fallback_url": "", - "sms_fallback_method": "POST", - "sms_application_sid": "", - "address_requirements": "none", - "beta": false, - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "capabilities": { - "voice": true, - "sms": true, - "mms": true - }, - "links": { - "phone_number": "https://api.twilio.com/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - } - ] - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers?PageSize=1&Page=0", - "key": "phone_numbers", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers?PageSize=1&Page=0" - }, - "phone_numbers": [] - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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/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_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/test_service.py b/tests/integration/verify/v2/test_service.py deleted file mode 100644 index becfc17065..0000000000 --- a/tests/integration/verify/v2/test_service.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 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, - "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" - } - } - ''' - )) - - 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, - "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" - } - } - ''' - )) - - 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, - "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" - } - } - ] - } - ''' - )) - - 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, - "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" - } - } - ''' - )) - - 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/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_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/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_token_pagination.py b/tests/unit/base/test_token_pagination.py new file mode 100644 index 0000000000..2de67831cd --- /dev/null +++ b/tests/unit/base/test_token_pagination.py @@ -0,0 +1,749 @@ +import unittest +from unittest.mock import Mock +from tests import IntegrationTestCase +from tests.holodeck import Request +from twilio.base.exceptions import TwilioException +from twilio.base.token_pagination import TokenPagination +from twilio.http.response import Response + + +class MockTokenPaginationPage(TokenPagination): + """Mock implementation of TokenPagination for testing""" + + def get_instance(self, payload): + return payload + + +class TokenPaginationPropertyTest(unittest.TestCase): + """Test TokenPagination property accessors""" + + def setUp(self): + self.version = Mock() + self.version.domain = Mock() + + # Mock response with token pagination format + self.payload = { + "meta": { + "key": "items", + "pageSize": 50, + "nextToken": "next_abc123", + "previousToken": "prev_xyz789", + }, + "items": [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}], + } + + self.response = Mock() + self.response.text = """ + { + "meta": { + "key": "items", + "pageSize": 50, + "nextToken": "next_abc123", + "previousToken": "prev_xyz789" + }, + "items": [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}] + } + """ + self.response.status_code = 200 + + self.solution = { + "account_sid": "ACxxxx", + } + self.page = MockTokenPaginationPage( + self.version, + self.response, + "/Accounts/ACxxxx/Resources.json", + {}, + self.solution, + ) + + def test_key_property(self): + """Test that key property returns the correct value""" + self.assertEqual(self.page.key, "items") + + def test_page_size_property(self): + """Test that page_size property returns the correct value""" + self.assertEqual(self.page.page_size, 50) + + def test_next_token_property(self): + """Test that next_token property returns the correct value""" + self.assertEqual(self.page.next_token, "next_abc123") + + def test_previous_token_property(self): + """Test that previous_token property returns the correct value""" + self.assertEqual(self.page.previous_token, "prev_xyz789") + + def test_properties_without_meta(self): + """Test that properties return None when meta is missing""" + response = Mock() + response.text = '{"items": []}' + response.status_code = 200 + + page = MockTokenPaginationPage( + self.version, response, "/Accounts/ACxxxx/Resources.json", {}, self.solution + ) + + self.assertIsNone(page.key) + self.assertIsNone(page.page_size) + self.assertIsNone(page.next_token) + self.assertIsNone(page.previous_token) + + def test_properties_with_partial_meta(self): + """Test that properties return None when specific keys are missing""" + response = Mock() + response.text = '{"meta": {"key": "items"}, "items": []}' + response.status_code = 200 + + page = MockTokenPaginationPage( + self.version, response, "/Accounts/ACxxxx/Resources.json", {}, self.solution + ) + + self.assertEqual(page.key, "items") + self.assertIsNone(page.page_size) + self.assertIsNone(page.next_token) + self.assertIsNone(page.previous_token) + + +class TokenPaginationNavigationTest(IntegrationTestCase): + """Test TokenPagination next_page and previous_page methods""" + + def setUp(self): + super(TokenPaginationNavigationTest, self).setUp() + + # Mock first page response + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page2", + "previousToken": null + }, + "items": [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Resources.json", + params={}, + ), + ) + + # Mock second page response (next page) + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page3", + "previousToken": "token_prev1" + }, + "items": [{"id": 3, "name": "Item 3"}, {"id": 4, "name": "Item 4"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Resources.json", + params={"pageToken": "token_page2"}, + ), + ) + + # Mock third page response (has no next) + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": null, + "previousToken": "token_prev2" + }, + "items": [{"id": 5, "name": "Item 5"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Resources.json", + params={"pageToken": "token_page3"}, + ), + ) + + # Mock previous page response (going back to page 1) + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page2", + "previousToken": null + }, + "items": [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Resources.json", + params={"pageToken": "token_prev1"}, + ), + ) + + # Mock going back from page 3 to page 2 + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page3", + "previousToken": "token_prev1" + }, + "items": [{"id": 3, "name": "Item 3"}, {"id": 4, "name": "Item 4"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Resources.json", + params={"pageToken": "token_prev2"}, + ), + ) + + self.version = self.client.api.v2010 + self.response = self.version.page( + method="GET", uri="/Accounts/ACaaaa/Resources.json" + ) + + self.solution = { + "account_sid": "ACaaaa", + } + + self.page = MockTokenPaginationPage( + self.version, + self.response, + "/Accounts/ACaaaa/Resources.json", + {}, + self.solution, + ) + + def test_next_page(self): + """Test that next_page() navigates to the next page using token""" + self.assertIsNotNone(self.page.next_token) + self.assertEqual(self.page.next_token, "token_page2") + + next_page = self.page.next_page() + + self.assertIsNotNone(next_page) + self.assertIsInstance(next_page, MockTokenPaginationPage) + # Verify we got the next page's data + self.assertEqual(next_page.next_token, "token_page3") + self.assertEqual(next_page.previous_token, "token_prev1") + + def test_next_page_none_when_no_token(self): + """Test that next_page() returns None when there's no next token""" + # Navigate to the last page + next_page = self.page.next_page() + last_page = next_page.next_page() + + # Last page should have no next token + self.assertIsNone(last_page.next_token) + + # next_page() should return None + result = last_page.next_page() + self.assertIsNone(result) + + def test_previous_page(self): + """Test that previous_page() navigates to the previous page using token""" + # Navigate to second page first + next_page = self.page.next_page() + self.assertIsNotNone(next_page.previous_token) + self.assertEqual(next_page.previous_token, "token_prev1") + + # Go back to previous page + prev_page = next_page.previous_page() + + self.assertIsNotNone(prev_page) + self.assertIsInstance(prev_page, MockTokenPaginationPage) + # Verify we got the first page's data + self.assertIsNone(prev_page.previous_token) + self.assertEqual(prev_page.next_token, "token_page2") + + def test_previous_page_none_when_no_token(self): + """Test that previous_page() returns None when there's no previous token""" + # First page should have no previous token + self.assertIsNone(self.page.previous_token) + + # previous_page() should return None + result = self.page.previous_page() + self.assertIsNone(result) + + def test_navigation_chain(self): + """Test navigating through multiple pages forward and backward""" + # Page 1 -> Page 2 + page2 = self.page.next_page() + self.assertEqual(page2.previous_token, "token_prev1") + + # Page 2 -> Page 3 + page3 = page2.next_page() + self.assertIsNone(page3.next_token) + self.assertEqual(page3.previous_token, "token_prev2") + + # Page 3 -> Page 2 (backward) + back_to_page2 = page3.previous_page() + self.assertIsNotNone(back_to_page2) + + +class TokenPaginationErrorTest(unittest.TestCase): + """Test TokenPagination error handling""" + + def test_next_page_without_uri_in_solution(self): + """Test that next_page() raises error when URI is missing""" + version = Mock() + response = Mock() + response.text = """ + { + "meta": { + "key": "items", + "pageSize": 50, + "nextToken": "abc123" + }, + "items": [] + } + """ + response.status_code = 200 + + # Solution without URI + solution = {"account_sid": "ACxxxx"} + + # Pass empty string as URI to test the error case + page = MockTokenPaginationPage(version, response, "", {}, solution) + + with self.assertRaises(TwilioException) as context: + page.next_page() + + self.assertIn("URI must be provided", str(context.exception)) + + +class TokenPaginationStreamTest(IntegrationTestCase): + """Test streaming with TokenPagination""" + + def setUp(self): + super(TokenPaginationStreamTest, self).setUp() + + # Mock page 1 + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "records", + "pageSize": 2, + "nextToken": "token_2" + }, + "records": [{"id": 1}, {"id": 2}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Records.json", + params={}, + ), + ) + + # Mock page 2 + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "records", + "pageSize": 2, + "nextToken": "token_3", + "previousToken": "token_2" + }, + "records": [{"id": 3}, {"id": 4}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Records.json", + params={"pageToken": "token_2"}, + ), + ) + + # Mock page 3 (final) + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "records", + "pageSize": 2, + "nextToken": null, + "previousToken": "token_3" + }, + "records": [{"id": 5}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Records.json", + params={"pageToken": "token_3"}, + ), + ) + + self.version = self.client.api.v2010 + self.response = self.version.page( + method="GET", uri="/Accounts/ACaaaa/Records.json" + ) + + self.solution = { + "account_sid": "ACaaaa", + } + + self.page = MockTokenPaginationPage( + self.version, + self.response, + "/Accounts/ACaaaa/Records.json", + {}, + self.solution, + ) + + def test_stream_all_records(self): + """Test streaming through all pages""" + records = list(self.version.stream(self.page)) + + self.assertEqual(len(records), 5) + self.assertEqual(records[0]["id"], 1) + self.assertEqual(records[4]["id"], 5) + + def test_stream_with_limit(self): + """Test streaming with a limit""" + records = list(self.version.stream(self.page, limit=3)) + + self.assertEqual(len(records), 3) + self.assertEqual(records[0]["id"], 1) + self.assertEqual(records[2]["id"], 3) + + def test_stream_with_page_limit(self): + """Test streaming with page limit""" + records = list(self.version.stream(self.page, page_limit=1)) + + # Only first page (2 records) + self.assertEqual(len(records), 2) + + +class TokenPaginationInternalMethodTest(unittest.TestCase): + """Test TokenPagination internal methods""" + + def setUp(self): + self.version = Mock() + self.version.domain = Mock() + self.version.domain.twilio = Mock() + self.version.domain.absolute_url = Mock( + side_effect=lambda uri: f"https://api.twilio.com{uri}" + ) + + # Mock first page response + self.first_response = Mock() + self.first_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page2", + "previousToken": null + }, + "items": [{"id": 1}, {"id": 2}] + } + """ + self.first_response.status_code = 200 + + # Mock next page response + self.next_response = Mock() + self.next_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": null, + "previousToken": "token_prev" + }, + "items": [{"id": 3}, {"id": 4}] + } + """ + self.next_response.status_code = 200 + + self.solution = {"account_sid": "ACxxxx"} + self.page = MockTokenPaginationPage( + self.version, + self.first_response, + "/Accounts/ACxxxx/Resources.json", + {}, + self.solution, + ) + + def test_get_page_with_valid_token(self): + """Test _get_page() with a valid token""" + self.version.page = Mock(return_value=self.next_response) + + result = self.page._get_page("token_page2") + + self.assertIsNotNone(result) + self.assertIsInstance(result, MockTokenPaginationPage) + self.version.page.assert_called_once_with( + method="GET", + uri="/Accounts/ACxxxx/Resources.json", + params={"pageToken": "token_page2"}, + ) + + def test_get_page_with_none_token(self): + """Test _get_page() with None token returns None""" + result = self.page._get_page(None) + self.assertIsNone(result) + + def test_get_page_without_uri(self): + """Test _get_page() raises error when URI is missing""" + page = MockTokenPaginationPage( + self.version, self.first_response, "", {}, self.solution + ) + + with self.assertRaises(TwilioException) as context: + page._get_page("some_token") + + self.assertIn("URI must be provided", str(context.exception)) + + def test_repr(self): + """Test __repr__ method returns correct string""" + self.assertEqual(repr(self.page), "") + + def test_params_preserved_across_pagination(self): + """Test that initial query params are preserved when fetching next page""" + # Create a page with initial query parameters + initial_params = {"status": "active", "limit": 50} + page_with_params = MockTokenPaginationPage( + self.version, + self.first_response, + "/Accounts/ACxxxx/Resources.json", + initial_params, + self.solution, + ) + + self.version.page = Mock(return_value=self.next_response) + + # Fetch the next page + result = page_with_params._get_page("token_page2") + + # Verify that the initial params are preserved and pageToken is added + self.assertIsNotNone(result) + self.version.page.assert_called_once_with( + method="GET", + uri="/Accounts/ACxxxx/Resources.json", + params={"status": "active", "limit": 50, "pageToken": "token_page2"}, + ) + + +class TokenPaginationAsyncTest(unittest.IsolatedAsyncioTestCase): + """Test TokenPagination async methods""" + + def setUp(self): + self.version = Mock() + self.version.domain = Mock() + self.version.domain.twilio = Mock() + self.version.domain.absolute_url = Mock( + side_effect=lambda uri: f"https://api.twilio.com{uri}" + ) + + # Mock first page response + self.first_response = Mock() + self.first_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page2", + "previousToken": null + }, + "items": [{"id": 1}, {"id": 2}] + } + """ + self.first_response.status_code = 200 + + # Mock next page response + self.next_response = Mock() + self.next_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page3", + "previousToken": "token_prev" + }, + "items": [{"id": 3}, {"id": 4}] + } + """ + self.next_response.status_code = 200 + + # Mock previous page response + self.prev_response = Mock() + self.prev_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page2", + "previousToken": null + }, + "items": [{"id": 1}, {"id": 2}] + } + """ + self.prev_response.status_code = 200 + + self.solution = {"account_sid": "ACxxxx"} + + # Page with next token + self.page = MockTokenPaginationPage( + self.version, + self.first_response, + "/Accounts/ACxxxx/Resources.json", + {}, + self.solution, + ) + + # Page with previous token (page 2) + self.page_with_prev = MockTokenPaginationPage( + self.version, + self.next_response, + "/Accounts/ACxxxx/Resources.json", + {}, + self.solution, + ) + + async def test_get_page_async_with_valid_token(self): + """Test _get_page_async() with a valid token""" + self.version.page = Mock(return_value=self.next_response) + + result = await self.page._get_page_async("token_page2") + + self.assertIsNotNone(result) + self.assertIsInstance(result, MockTokenPaginationPage) + self.version.page.assert_called_once_with( + method="GET", + uri="/Accounts/ACxxxx/Resources.json", + params={"pageToken": "token_page2"}, + ) + + async def test_get_page_async_with_none_token(self): + """Test _get_page_async() with None token returns None""" + result = await self.page._get_page_async(None) + self.assertIsNone(result) + + async def test_get_page_async_without_uri(self): + """Test _get_page_async() raises error when URI is missing""" + page = MockTokenPaginationPage( + self.version, self.first_response, "", {}, self.solution + ) + + with self.assertRaises(TwilioException) as context: + await page._get_page_async("some_token") + + self.assertIn("URI must be provided", str(context.exception)) + + async def test_next_page_async(self): + """Test next_page_async() navigates to next page""" + self.version.page = Mock(return_value=self.next_response) + + next_page = await self.page.next_page_async() + + self.assertIsNotNone(next_page) + self.assertIsInstance(next_page, MockTokenPaginationPage) + self.assertEqual(next_page.next_token, "token_page3") + self.assertEqual(next_page.previous_token, "token_prev") + + async def test_next_page_async_none_when_no_token(self): + """Test next_page_async() returns None when there's no next token""" + # Create page with no next token + no_next_response = Mock() + no_next_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": null, + "previousToken": "token_prev" + }, + "items": [{"id": 5}] + } + """ + no_next_response.status_code = 200 + + page = MockTokenPaginationPage( + self.version, + no_next_response, + "/Accounts/ACxxxx/Resources.json", + {}, + self.solution, + ) + + result = await page.next_page_async() + self.assertIsNone(result) + + async def test_previous_page_async(self): + """Test previous_page_async() navigates to previous page""" + self.version.page = Mock(return_value=self.prev_response) + + prev_page = await self.page_with_prev.previous_page_async() + + self.assertIsNotNone(prev_page) + self.assertIsInstance(prev_page, MockTokenPaginationPage) + self.assertIsNone(prev_page.previous_token) + self.assertEqual(prev_page.next_token, "token_page2") + + async def test_previous_page_async_none_when_no_token(self): + """Test previous_page_async() returns None when there's no previous token""" + # First page has no previous token + result = await self.page.previous_page_async() + self.assertIsNone(result) + + async def test_params_preserved_across_pagination_async(self): + """Test that initial query params are preserved when fetching next page async""" + # Create a page with initial query parameters + initial_params = {"status": "active", "limit": 50} + page_with_params = MockTokenPaginationPage( + self.version, + self.first_response, + "/Accounts/ACxxxx/Resources.json", + initial_params, + self.solution, + ) + + self.version.page = Mock(return_value=self.next_response) + + # Fetch the next page + result = await page_with_params._get_page_async("token_page2") + + # Verify that the initial params are preserved and pageToken is added + self.assertIsNotNone(result) + self.version.page.assert_called_once_with( + method="GET", + uri="/Accounts/ACxxxx/Resources.json", + params={"status": "active", "limit": 50, "pageToken": "token_page2"}, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/base/test_version.py b/tests/unit/base/test_version.py new file mode 100644 index 0000000000..03c684a2ff --- /dev/null +++ b/tests/unit/base/test_version.py @@ -0,0 +1,1239 @@ +import unittest +from unittest.mock import Mock + +import aiounittest +from tests import IntegrationTestCase +from tests.holodeck import Request +from twilio.base.version import Version +from twilio.base.exceptions import ( + TwilioRestException, + TwilioServiceException, + TwilioException, +) +from twilio.base.page import Page +from twilio.http.response import Response + + +class TestPage(Page): + def get_instance(self, payload): + return payload + + +class StreamTestCase(IntegrationTestCase): + def setUp(self): + super(StreamTestCase, self).setUp() + + self.holodeck.mock( + Response( + 200, + """ + { + "next_page_uri": "/2010-04-01/Accounts/AC123/Messages.json?Page=1", + "messages": [{"body": "payload0"}, {"body": "payload1"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json" + ), + ) + + self.holodeck.mock( + Response( + 200, + """ + { + "next_page_uri": "/2010-04-01/Accounts/AC123/Messages.json?Page=2", + "messages": [{"body": "payload2"}, {"body": "payload3"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json?Page=1" + ), + ) + + self.holodeck.mock( + Response( + 200, + """ + { + "next_page_uri": null, + "messages": [{"body": "payload4"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json?Page=2" + ), + ) + + self.version = self.client.api.v2010 + self.response = self.version.page( + method="GET", uri="/Accounts/AC123/Messages.json" + ) + self.page = TestPage(self.version, self.response, {}) + + def test_stream(self): + messages = list(self.version.stream(self.page)) + + self.assertEqual(len(messages), 5) + + def test_stream_limit(self): + messages = list(self.version.stream(self.page, limit=3)) + + self.assertEqual(len(messages), 3) + + def test_stream_page_limit(self): + messages = list(self.version.stream(self.page, page_limit=1)) + + self.assertEqual(len(messages), 2) + + +class VersionTestCase(IntegrationTestCase): + def test_fetch_redirect(self): + self.holodeck.mock( + Response(307, '{"redirect_to": "some_place"}'), + Request(url="https://messaging.twilio.com/v1/Deactivations"), + ) + response = self.client.messaging.v1.fetch(method="GET", uri="/Deactivations") + + self.assertIsNotNone(response) + + def test_delete_success(self): + self.holodeck.mock( + Response(201, ""), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + result = self.client.api.v2010.delete( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + + self.assertTrue(result) + + def test_delete_not_found(self): + self.holodeck.mock( + Response(404, '{"message": "Resource not found"}'), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM456.json", + ), + ) + + with self.assertRaises(Exception) as context: + self.client.api.v2010.delete( + method="DELETE", uri="/Accounts/AC123/Messages/MM456.json" + ) + + self.assertIn("Unable to delete record", str(context.exception)) + + def test_delete_with_response_body(self): + """Test delete that returns JSON response body (V1 API style)""" + self.holodeck.mock( + Response( + 202, + '{"sid": "DE123", "status": "deleted", "account_sid": "AC123"}', + ), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result = self.client.api.v2010.delete( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + + self.assertIsInstance(result, dict) + self.assertEqual(result["sid"], "DE123") + self.assertEqual(result["status"], "deleted") + self.assertEqual(result["account_sid"], "AC123") + + def test_delete_no_content(self): + """Test traditional delete with no content (204)""" + self.holodeck.mock( + Response(204, ""), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + result = self.client.api.v2010.delete( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + + self.assertTrue(result) + self.assertIsInstance(result, bool) + + def test_delete_with_invalid_json(self): + """Test delete with response content that is not valid JSON""" + self.holodeck.mock( + Response(200, "Not valid JSON content"), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result = self.client.api.v2010.delete( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + + # Should fallback to boolean True when JSON parsing fails + self.assertTrue(result) + self.assertIsInstance(result, bool) + + +class VersionExceptionTestCase(unittest.TestCase): + """Test cases for base Version.exception() method with RFC-9457 auto-detection""" + + def test_exception_rfc9457_auto_detection(self): + """Test that base Version auto-detects RFC-9457 errors and creates TwilioServiceException""" + response = Mock(spec=Response) + response.status_code = 400 + response.text = """{ + "type": "https://www.twilio.com/docs/api/errors/20001", + "title": "Invalid parameter", + "status": 400, + "code": 20001, + "detail": "The 'PhoneNumber' parameter is required.", + "instance": "/api/v1/accounts/AC123/calls/CA456" + }""" + + exception = Version.exception( + method="POST", uri="/test", response=response, message="Test error" + ) + + self.assertIsInstance(exception, TwilioServiceException) + self.assertEqual(exception.type, "https://www.twilio.com/docs/api/errors/20001") + self.assertEqual(exception.title, "Invalid parameter") + self.assertEqual(exception.status, 400) + self.assertEqual(exception.code, 20001) + self.assertEqual(exception.detail, "The 'PhoneNumber' parameter is required.") + self.assertEqual(exception.instance, "/api/v1/accounts/AC123/calls/CA456") + self.assertEqual(exception.method, "POST") + self.assertEqual(exception.uri, "/test") + + def test_exception_legacy_format_fallback(self): + """Test that base Version falls back to TwilioRestException for legacy errors""" + response = Mock(spec=Response) + response.status_code = 400 + response.text = """{ + "message": "Invalid phone number", + "code": 21211 + }""" + + exception = Version.exception( + method="POST", uri="/test", response=response, message="Test error" + ) + + self.assertIsInstance(exception, TwilioRestException) + self.assertEqual(exception.status, 400) + self.assertEqual(exception.code, 21211) + self.assertIn("Invalid phone number", exception.msg) + + def test_exception_rfc9457_with_validation_errors_base_version(self): + """Test base Version handles RFC-9457 with validation errors array""" + response = Mock(spec=Response) + response.status_code = 422 + response.text = """{ + "type": "https://www.twilio.com/docs/api/errors/20001", + "title": "Validation failed", + "status": 422, + "code": 20001, + "detail": "Request validation failed", + "errors": [ + {"detail": "must be a positive integer", "pointer": "#/age"}, + {"detail": "must be 'green', 'red' or 'blue'", "pointer": "#/profile/color"} + ] + }""" + + exception = Version.exception( + method="POST", uri="/test", response=response, message="Validation error" + ) + + self.assertIsInstance(exception, TwilioServiceException) + self.assertEqual(exception.title, "Validation failed") + self.assertEqual(len(exception.errors), 2) + self.assertEqual(exception.errors[0]["detail"], "must be a positive integer") + self.assertEqual(exception.errors[0]["pointer"], "#/age") + + def test_exception_malformed_json_fallback(self): + """Test that base Version handles malformed JSON gracefully""" + response = Mock(spec=Response) + response.status_code = 500 + response.text = "This is not JSON" + + exception = Version.exception( + method="GET", uri="/test", response=response, message="Server error" + ) + + self.assertIsInstance(exception, TwilioRestException) + self.assertEqual(exception.status, 500) + + +class TwilioServiceExceptionTestCase(unittest.TestCase): + """Comprehensive test cases for TwilioServiceException""" + + def test_minimal_required_fields(self): + """Test TwilioServiceException with only required fields""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20003", + title="Authentication Failed", + status=401, + code=20003, + ) + + self.assertEqual(exc.type, "https://www.twilio.com/docs/api/errors/20003") + self.assertEqual(exc.title, "Authentication Failed") + self.assertEqual(exc.status, 401) + self.assertEqual(exc.code, 20003) + self.assertIsNone(exc.detail) + self.assertIsNone(exc.instance) + self.assertEqual(exc.errors, []) + self.assertEqual(exc.method, "GET") + self.assertEqual(exc.uri, "") + + def test_all_fields_populated(self): + """Test TwilioServiceException with all fields populated""" + errors = [ + {"detail": "Field is required", "pointer": "#/name"}, + {"detail": "Must be a valid email", "pointer": "#/email"}, + ] + + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Invalid Request", + status=400, + code=20001, + detail="The request could not be processed", + instance="/api/v1/accounts/AC123/messages/SM456", + errors=errors, + method="POST", + uri="/api/v1/messages", + ) + + self.assertEqual(exc.type, "https://www.twilio.com/docs/api/errors/20001") + self.assertEqual(exc.title, "Invalid Request") + self.assertEqual(exc.status, 400) + self.assertEqual(exc.code, 20001) + self.assertEqual(exc.detail, "The request could not be processed") + self.assertEqual(exc.instance, "/api/v1/accounts/AC123/messages/SM456") + self.assertEqual(len(exc.errors), 2) + self.assertEqual(exc.errors[0]["detail"], "Field is required") + self.assertEqual(exc.errors[0]["pointer"], "#/name") + self.assertEqual(exc.method, "POST") + self.assertEqual(exc.uri, "/api/v1/messages") + + def test_partial_optional_fields(self): + """Test TwilioServiceException with some optional fields""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20002", + title="Rate Limit Exceeded", + status=429, + code=20002, + detail="Too many requests", + method="POST", + uri="/api/v1/calls", + ) + + self.assertEqual(exc.detail, "Too many requests") + self.assertIsNone(exc.instance) + self.assertEqual(exc.errors, []) + self.assertEqual(exc.method, "POST") + self.assertEqual(exc.uri, "/api/v1/calls") + + def test_empty_errors_array(self): + """Test TwilioServiceException with explicitly empty errors array""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Bad Request", + status=400, + code=20001, + errors=[], + ) + + self.assertEqual(exc.errors, []) + + def test_none_errors_becomes_empty_list(self): + """Test that None errors parameter becomes empty list""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Bad Request", + status=400, + code=20001, + errors=None, + ) + + self.assertEqual(exc.errors, []) + self.assertIsInstance(exc.errors, list) + + def test_different_http_methods(self): + """Test TwilioServiceException with different HTTP methods""" + methods = ["GET", "POST", "PUT", "PATCH", "DELETE"] + + for method in methods: + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Error", + status=400, + code=20001, + method=method, + ) + self.assertEqual(exc.method, method) + + def test_different_status_codes(self): + """Test TwilioServiceException with various HTTP status codes""" + status_codes = [400, 401, 403, 404, 422, 429, 500, 502, 503] + + for status_code in status_codes: + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Error", + status=status_code, + code=20001, + ) + self.assertEqual(exc.status, status_code) + + def test_string_representation_non_tty(self): + """Test __str__ method for non-TTY output (plain text)""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Invalid Parameter", + status=400, + code=20001, + detail="The PhoneNumber parameter is required", + ) + + # Mock sys.stderr to simulate non-TTY + import sys + + original_stderr = sys.stderr + try: + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=False) + + result = str(exc) + + self.assertIn("HTTP 400 error", result) + self.assertIn("Invalid Parameter", result) + self.assertIn("The PhoneNumber parameter is required", result) + finally: + sys.stderr = original_stderr + + def test_string_representation_non_tty_with_validation_errors(self): + """Test __str__ method for non-TTY with validation errors""" + errors = [ + {"detail": "must be positive", "pointer": "#/age"}, + {"detail": "must be valid email", "pointer": "#/email"}, + ] + + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Validation Failed", + status=422, + code=20001, + detail="Request validation failed", + errors=errors, + ) + + import sys + + original_stderr = sys.stderr + try: + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=False) + + result = str(exc) + + self.assertIn("HTTP 422 error", result) + self.assertIn("Validation Failed", result) + self.assertIn("Request validation failed", result) + self.assertIn("Validation errors", result) + self.assertIn("#/age", result) + self.assertIn("must be positive", result) + finally: + sys.stderr = original_stderr + + def test_string_representation_tty(self): + """Test __str__ method for TTY output (colored)""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Invalid Parameter", + status=400, + code=20001, + detail="The PhoneNumber parameter is required", + instance="/api/v1/accounts/AC123/calls/CA456", + method="POST", + uri="/api/v1/calls", + ) + + import sys + + original_stderr = sys.stderr + try: + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=True) + + result = str(exc) + + # Check for ANSI escape codes (color formatting) + self.assertIn("\033[", result) + # Check for content + self.assertIn("HTTP Error", result) + self.assertIn("POST /api/v1/calls", result) + self.assertIn("Invalid Parameter", result) + self.assertIn("The PhoneNumber parameter is required", result) + self.assertIn("400", result) + self.assertIn("20001", result) + self.assertIn("https://www.twilio.com/docs/api/errors/20001", result) + finally: + sys.stderr = original_stderr + + def test_string_representation_tty_with_validation_errors(self): + """Test __str__ method for TTY with validation errors (colored)""" + errors = [ + {"detail": "must be positive", "pointer": "#/age"}, + {"detail": "must be valid", "pointer": "#/email"}, + ] + + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Validation Failed", + status=422, + code=20001, + errors=errors, + method="POST", + uri="/api/v1/users", + ) + + import sys + + original_stderr = sys.stderr + try: + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=True) + + result = str(exc) + + self.assertIn("Validation Errors", result) + self.assertIn("#/age", result) + self.assertIn("must be positive", result) + self.assertIn("#/email", result) + self.assertIn("must be valid", result) + finally: + sys.stderr = original_stderr + + def test_string_representation_tty_no_uri(self): + """Test __str__ method when uri is empty""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Error", + status=400, + code=20001, + method="GET", + uri="", + ) + + import sys + + original_stderr = sys.stderr + try: + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=True) + + result = str(exc) + + self.assertIn("(no URI)", result) + finally: + sys.stderr = original_stderr + + def test_validation_errors_with_missing_fields(self): + """Test validation errors with missing detail or pointer fields""" + errors = [ + {"detail": "error detail"}, # missing pointer + {"pointer": "#/field"}, # missing detail + {}, # both missing + ] + + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Validation Failed", + status=422, + code=20001, + errors=errors, + ) + + import sys + + original_stderr = sys.stderr + try: + # Test non-TTY output + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=False) + + result = str(exc) + # Should handle missing fields gracefully + self.assertIn("Validation errors", result) + finally: + sys.stderr = original_stderr + + def test_multiple_validation_errors(self): + """Test with multiple validation errors""" + errors = [ + {"detail": "Field is required", "pointer": "#/firstName"}, + {"detail": "Must be at least 18", "pointer": "#/age"}, + {"detail": "Invalid format", "pointer": "#/phoneNumber"}, + {"detail": "Must be unique", "pointer": "#/email"}, + ] + + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Validation Failed", + status=422, + code=20001, + errors=errors, + ) + + self.assertEqual(len(exc.errors), 4) + self.assertEqual(exc.errors[2]["pointer"], "#/phoneNumber") + self.assertEqual(exc.errors[3]["detail"], "Must be unique") + + def test_exception_as_parent_class(self): + """Test that TwilioServiceException is a proper exception""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Error", + status=400, + code=20001, + ) + + self.assertIsInstance(exc, Exception) + self.assertIsInstance(exc, TwilioException) + + def test_exception_can_be_raised_and_caught(self): + """Test that TwilioServiceException can be raised and caught""" + with self.assertRaises(TwilioServiceException) as context: + raise TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Test Error", + status=400, + code=20001, + ) + + self.assertEqual(context.exception.title, "Test Error") + self.assertEqual(context.exception.code, 20001) + + +class ResponseInfoIntegrationTestCase(IntegrationTestCase): + """Integration tests for *_with_response_info methods""" + + def test_fetch_with_response_info(self): + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123", "name": "Test Account"}', + {"X-Custom-Header": "test-value"}, + ), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = self.client.api.v2010.fetch_with_response_info( + method="GET", uri="/Accounts/AC123.json" + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(payload["name"], "Test Account") + self.assertEqual(status_code, 200) + self.assertIn("X-Custom-Header", headers) + self.assertEqual(headers["X-Custom-Header"], "test-value") + + def test_update_with_response_info(self): + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123", "name": "Updated Account"}', + {"X-Update-Header": "updated"}, + ), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123.json", + ), + ) + payload, status_code, headers = self.client.api.v2010.update_with_response_info( + method="POST", uri="/Accounts/AC123.json", data={"name": "Updated Account"} + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(payload["name"], "Updated Account") + self.assertEqual(status_code, 200) + self.assertIn("X-Update-Header", headers) + + def test_delete_with_response_info(self): + self.holodeck.mock( + Response(204, "", {"X-Delete-Header": "deleted"}), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + success, status_code, headers = self.client.api.v2010.delete_with_response_info( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + + self.assertTrue(success) + self.assertEqual(status_code, 204) + self.assertIn("X-Delete-Header", headers) + + def test_create_with_response_info(self): + self.holodeck.mock( + Response( + 201, + '{"sid": "MM123", "body": "Hello World"}', + {"X-Create-Header": "created"}, + ), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json", + ), + ) + payload, status_code, headers = self.client.api.v2010.create_with_response_info( + method="POST", + uri="/Accounts/AC123/Messages.json", + data={"body": "Hello World"}, + ) + + self.assertEqual(payload["sid"], "MM123") + self.assertEqual(payload["body"], "Hello World") + self.assertEqual(status_code, 201) + self.assertIn("X-Create-Header", headers) + + def test_page_with_response_info(self): + self.holodeck.mock( + Response( + 200, + '{"messages": [], "next_page_uri": null}', + {"X-Page-Header": "page"}, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json" + ), + ) + response, status_code, headers = self.client.api.v2010.page_with_response_info( + method="GET", uri="/Accounts/AC123/Messages.json" + ) + + self.assertIsNotNone(response) + self.assertEqual(status_code, 200) + self.assertIn("X-Page-Header", headers) + + def test_fetch_with_response_info_error(self): + self.holodeck.mock( + Response(404, '{"message": "Resource not found"}'), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC456.json"), + ) + + with self.assertRaises(Exception) as context: + self.client.api.v2010.fetch_with_response_info( + method="GET", uri="/Accounts/AC456.json" + ) + + self.assertIn("Unable to fetch record", str(context.exception)) + + def test_update_with_response_info_error(self): + self.holodeck.mock( + Response(400, '{"message": "Invalid request"}'), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123.json", + ), + ) + + with self.assertRaises(Exception) as context: + self.client.api.v2010.update_with_response_info( + method="POST", uri="/Accounts/AC123.json", data={"invalid": "data"} + ) + + self.assertIn("Unable to update record", str(context.exception)) + + def test_delete_with_response_info_error(self): + self.holodeck.mock( + Response(404, '{"message": "Resource not found"}'), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM456.json", + ), + ) + + with self.assertRaises(Exception) as context: + self.client.api.v2010.delete_with_response_info( + method="DELETE", uri="/Accounts/AC123/Messages/MM456.json" + ) + + self.assertIn("Unable to delete record", str(context.exception)) + + def test_delete_with_response_info_json_body(self): + """Test delete_with_response_info with JSON response body""" + self.holodeck.mock( + Response( + 202, + '{"sid": "DE123", "status": "deleted", "account_sid": "AC123"}', + {"X-Delete-Header": "deleted", "X-Request-Id": "req123"}, + ), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result, status_code, headers = self.client.api.v2010.delete_with_response_info( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + + self.assertIsInstance(result, dict) + self.assertEqual(result["sid"], "DE123") + self.assertEqual(result["status"], "deleted") + self.assertEqual(result["account_sid"], "AC123") + self.assertEqual(status_code, 202) + self.assertIn("X-Delete-Header", headers) + self.assertEqual(headers["X-Delete-Header"], "deleted") + self.assertIn("X-Request-Id", headers) + + def test_delete_with_response_info_no_content(self): + """Test delete_with_response_info with no content (returns boolean)""" + self.holodeck.mock( + Response(204, "", {"X-Delete-Header": "success"}), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + result, status_code, headers = self.client.api.v2010.delete_with_response_info( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + + self.assertTrue(result) + self.assertIsInstance(result, bool) + self.assertEqual(status_code, 204) + self.assertIn("X-Delete-Header", headers) + + def test_delete_with_response_info_invalid_json(self): + """Test delete_with_response_info with invalid JSON content""" + self.holodeck.mock( + Response( + 200, + "Not valid JSON", + {"X-Delete-Header": "deleted"}, + ), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result, status_code, headers = self.client.api.v2010.delete_with_response_info( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + + # Should fallback to boolean True when JSON parsing fails + self.assertTrue(result) + self.assertIsInstance(result, bool) + self.assertEqual(status_code, 200) + self.assertIn("X-Delete-Header", headers) + + def test_create_with_response_info_error(self): + self.holodeck.mock( + Response(400, '{"message": "Invalid request"}'), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json", + ), + ) + + with self.assertRaises(Exception) as context: + self.client.api.v2010.create_with_response_info( + method="POST", + uri="/Accounts/AC123/Messages.json", + data={"invalid": "data"}, + ) + + self.assertIn("Unable to create record", str(context.exception)) + + def test_fetch_with_response_info_empty_headers(self): + self.holodeck.mock( + Response(200, '{"sid": "AC123", "name": "Test Account"}', None), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = self.client.api.v2010.fetch_with_response_info( + method="GET", uri="/Accounts/AC123.json" + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(status_code, 200) + self.assertIsInstance(headers, dict) + self.assertEqual(len(headers), 0) + + def test_fetch_with_response_info_multiple_headers(self): + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123"}', + { + "X-Custom-Header-1": "value1", + "X-Custom-Header-2": "value2", + "Content-Type": "application/json", + }, + ), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = self.client.api.v2010.fetch_with_response_info( + method="GET", uri="/Accounts/AC123.json" + ) + + self.assertEqual(status_code, 200) + self.assertIn("X-Custom-Header-1", headers) + self.assertIn("X-Custom-Header-2", headers) + self.assertIn("Content-Type", headers) + self.assertEqual(headers["X-Custom-Header-1"], "value1") + self.assertEqual(headers["X-Custom-Header-2"], "value2") + + def test_fetch_with_response_info_returns_tuple(self): + self.holodeck.mock( + Response(200, '{"sid": "AC123"}', {"X-Test": "test"}), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + result = self.client.api.v2010.fetch_with_response_info( + method="GET", uri="/Accounts/AC123.json" + ) + + self.assertIsInstance(result, tuple) + self.assertEqual(len(result), 3) + payload, status_code, headers = result + self.assertIsInstance(payload, dict) + self.assertIsInstance(status_code, int) + self.assertIsInstance(headers, dict) + + +class AsyncVersionTestCase(aiounittest.AsyncTestCase): + def setUp(self): + from tests.holodeck import AsyncHolodeck + from twilio.rest import Client + + self.holodeck = AsyncHolodeck() + self.client = Client( + "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "AUTHTOKEN", http_client=self.holodeck + ) + + async def test_fetch_with_response_info_async(self): + """Test fetch_with_response_info_async method""" + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123", "name": "Test Account"}', + {"X-Custom-Header": "test-value"}, + ), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = ( + await self.client.api.v2010.fetch_with_response_info_async( + method="GET", uri="/Accounts/AC123.json" + ) + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(payload["name"], "Test Account") + self.assertEqual(status_code, 200) + self.assertIn("X-Custom-Header", headers) + self.assertEqual(headers["X-Custom-Header"], "test-value") + + async def test_update_with_response_info_async(self): + """Test update_with_response_info_async method""" + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123", "name": "Updated Account"}', + {"X-Update-Header": "updated"}, + ), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123.json", + ), + ) + payload, status_code, headers = ( + await self.client.api.v2010.update_with_response_info_async( + method="POST", + uri="/Accounts/AC123.json", + data={"name": "Updated Account"}, + ) + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(payload["name"], "Updated Account") + self.assertEqual(status_code, 200) + self.assertIn("X-Update-Header", headers) + + async def test_delete_with_response_info_async(self): + """Test delete_with_response_info_async method""" + self.holodeck.mock( + Response(204, "", {"X-Delete-Header": "deleted"}), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + success, status_code, headers = ( + await self.client.api.v2010.delete_with_response_info_async( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + ) + + self.assertTrue(success) + self.assertEqual(status_code, 204) + self.assertIn("X-Delete-Header", headers) + + async def test_create_with_response_info_async(self): + """Test create_with_response_info_async method""" + self.holodeck.mock( + Response( + 201, + '{"sid": "MM123", "body": "Hello World"}', + {"X-Create-Header": "created"}, + ), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json", + ), + ) + payload, status_code, headers = ( + await self.client.api.v2010.create_with_response_info_async( + method="POST", + uri="/Accounts/AC123/Messages.json", + data={"body": "Hello World"}, + ) + ) + + self.assertEqual(payload["sid"], "MM123") + self.assertEqual(payload["body"], "Hello World") + self.assertEqual(status_code, 201) + self.assertIn("X-Create-Header", headers) + + async def test_page_with_response_info_async(self): + """Test page_with_response_info_async method""" + self.holodeck.mock( + Response( + 200, + '{"messages": [], "next_page_uri": null}', + {"X-Page-Header": "page"}, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json" + ), + ) + response, status_code, headers = ( + await self.client.api.v2010.page_with_response_info_async( + method="GET", uri="/Accounts/AC123/Messages.json" + ) + ) + + self.assertIsNotNone(response) + self.assertEqual(status_code, 200) + self.assertIn("X-Page-Header", headers) + + async def test_fetch_with_response_info_async_error(self): + """Test fetch_with_response_info_async method with error""" + self.holodeck.mock( + Response(404, '{"message": "Resource not found"}'), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC456.json"), + ) + + with self.assertRaises(Exception) as context: + await self.client.api.v2010.fetch_with_response_info_async( + method="GET", uri="/Accounts/AC456.json" + ) + + self.assertIn("Unable to fetch record", str(context.exception)) + + async def test_update_with_response_info_async_error(self): + """Test update_with_response_info_async method with error""" + self.holodeck.mock( + Response(400, '{"message": "Invalid request"}'), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123.json", + ), + ) + + with self.assertRaises(Exception) as context: + await self.client.api.v2010.update_with_response_info_async( + method="POST", uri="/Accounts/AC123.json", data={"invalid": "data"} + ) + + self.assertIn("Unable to update record", str(context.exception)) + + async def test_delete_with_response_info_async_error(self): + """Test delete_with_response_info_async method with error""" + self.holodeck.mock( + Response(404, '{"message": "Resource not found"}'), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM456.json", + ), + ) + + with self.assertRaises(Exception) as context: + await self.client.api.v2010.delete_with_response_info_async( + method="DELETE", uri="/Accounts/AC123/Messages/MM456.json" + ) + + self.assertIn("Unable to delete record", str(context.exception)) + + async def test_delete_with_response_info_async_json_body(self): + """Test delete_with_response_info_async with JSON response body""" + self.holodeck.mock( + Response( + 202, + '{"sid": "DE123", "status": "deleted", "account_sid": "AC123"}', + {"X-Delete-Header": "deleted", "X-Request-Id": "req123"}, + ), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result, status_code, headers = ( + await self.client.api.v2010.delete_with_response_info_async( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + ) + + self.assertIsInstance(result, dict) + self.assertEqual(result["sid"], "DE123") + self.assertEqual(result["status"], "deleted") + self.assertEqual(result["account_sid"], "AC123") + self.assertEqual(status_code, 202) + self.assertIn("X-Delete-Header", headers) + self.assertEqual(headers["X-Delete-Header"], "deleted") + self.assertIn("X-Request-Id", headers) + + async def test_delete_with_response_info_async_no_content(self): + """Test delete_with_response_info_async with no content (returns boolean)""" + self.holodeck.mock( + Response(204, "", {"X-Delete-Header": "success"}), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + result, status_code, headers = ( + await self.client.api.v2010.delete_with_response_info_async( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + ) + + self.assertTrue(result) + self.assertIsInstance(result, bool) + self.assertEqual(status_code, 204) + self.assertIn("X-Delete-Header", headers) + + async def test_delete_with_response_info_async_invalid_json(self): + """Test delete_with_response_info_async with invalid JSON content""" + self.holodeck.mock( + Response( + 200, + "Not valid JSON", + {"X-Delete-Header": "deleted"}, + ), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result, status_code, headers = ( + await self.client.api.v2010.delete_with_response_info_async( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + ) + + # Should fallback to boolean True when JSON parsing fails + self.assertTrue(result) + self.assertIsInstance(result, bool) + self.assertEqual(status_code, 200) + self.assertIn("X-Delete-Header", headers) + + async def test_create_with_response_info_async_error(self): + """Test create_with_response_info_async method with error""" + self.holodeck.mock( + Response(400, '{"message": "Invalid request"}'), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json", + ), + ) + + with self.assertRaises(Exception) as context: + await self.client.api.v2010.create_with_response_info_async( + method="POST", + uri="/Accounts/AC123/Messages.json", + data={"invalid": "data"}, + ) + + self.assertIn("Unable to create record", str(context.exception)) + + async def test_fetch_with_response_info_async_empty_headers(self): + """Test fetch_with_response_info_async with None headers""" + self.holodeck.mock( + Response(200, '{"sid": "AC123", "name": "Test Account"}', None), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = ( + await self.client.api.v2010.fetch_with_response_info_async( + method="GET", uri="/Accounts/AC123.json" + ) + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(status_code, 200) + self.assertIsInstance(headers, dict) + self.assertEqual(len(headers), 0) + + async def test_fetch_with_response_info_async_multiple_headers(self): + """Test fetch_with_response_info_async with multiple headers""" + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123"}', + { + "X-Custom-Header-1": "value1", + "X-Custom-Header-2": "value2", + "Content-Type": "application/json", + }, + ), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = ( + await self.client.api.v2010.fetch_with_response_info_async( + method="GET", uri="/Accounts/AC123.json" + ) + ) + + self.assertEqual(status_code, 200) + self.assertIn("X-Custom-Header-1", headers) + self.assertIn("X-Custom-Header-2", headers) + self.assertIn("Content-Type", headers) + self.assertEqual(headers["X-Custom-Header-1"], "value1") + self.assertEqual(headers["X-Custom-Header-2"], "value2") + + async def test_fetch_with_response_info_async_returns_tuple(self): + """Test that fetch_with_response_info_async returns proper tuple structure""" + self.holodeck.mock( + Response(200, '{"sid": "AC123"}', {"X-Test": "test"}), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + result = await self.client.api.v2010.fetch_with_response_info_async( + method="GET", uri="/Accounts/AC123.json" + ) + + self.assertIsInstance(result, tuple) + self.assertEqual(len(result), 3) + payload, status_code, headers = result + self.assertIsInstance(payload, dict) + self.assertIsInstance(status_code, int) + self.assertIsInstance(headers, dict) diff --git a/tests/unit/http/test_api_response.py b/tests/unit/http/test_api_response.py new file mode 100644 index 0000000000..4a1572b24c --- /dev/null +++ b/tests/unit/http/test_api_response.py @@ -0,0 +1,96 @@ +import unittest +from twilio.base.api_response import ApiResponse + + +class TestApiResponse(unittest.TestCase): + def test_initialization(self): + """Test ApiResponse initialization""" + data = {"sid": "AC123", "friendly_name": "Test"} + response = ApiResponse( + data=data, status_code=200, headers={"Content-Type": "application/json"} + ) + + self.assertEqual(response.data, data) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.headers["Content-Type"], "application/json") + + def test_repr(self): + """Test string representation""" + response = ApiResponse(data={"test": "data"}, status_code=201, headers={}) + repr_str = repr(response) + self.assertIn("201", repr_str) + self.assertIn("dict", repr_str) + + def test_str(self): + """Test human-readable string representation""" + response = ApiResponse(data={"test": "data"}, status_code=200, headers={}) + str_repr = str(response) + self.assertIn("200", str_repr) + self.assertIn("dict", str_repr) + + def test_with_list_data(self): + """Test ApiResponse with list data""" + data = [{"sid": "AC1"}, {"sid": "AC2"}] + response = ApiResponse(data=data, status_code=200, headers={}) + self.assertEqual(len(response.data), 2) + self.assertEqual(response.status_code, 200) + + def test_with_boolean_data(self): + """Test ApiResponse with boolean data (delete operations)""" + response = ApiResponse(data=True, status_code=204, headers={}) + self.assertTrue(response.data) + self.assertEqual(response.status_code, 204) + + def test_with_different_status_codes(self): + """Test ApiResponse with various status codes""" + # Test 201 Created + response_201 = ApiResponse(data={"created": True}, status_code=201, headers={}) + self.assertEqual(response_201.status_code, 201) + + # Test 204 No Content + response_204 = ApiResponse(data=True, status_code=204, headers={}) + self.assertEqual(response_204.status_code, 204) + + # Test 200 OK + response_200 = ApiResponse(data={"ok": True}, status_code=200, headers={}) + self.assertEqual(response_200.status_code, 200) + + def test_headers_access(self): + """Test accessing various headers""" + headers = { + "Content-Type": "application/json", + "X-RateLimit-Remaining": "100", + "X-RateLimit-Limit": "1000", + } + response = ApiResponse(data={"test": "data"}, status_code=200, headers=headers) + + self.assertEqual(response.headers["Content-Type"], "application/json") + self.assertEqual(response.headers["X-RateLimit-Remaining"], "100") + self.assertEqual(response.headers["X-RateLimit-Limit"], "1000") + + def test_empty_headers(self): + """Test ApiResponse with empty headers""" + response = ApiResponse(data={"test": "data"}, status_code=200, headers={}) + self.assertEqual(response.headers, {}) + + def test_data_attribute_types(self): + """Test that data attribute can hold various types""" + # Dictionary data + dict_response = ApiResponse(data={"key": "value"}, status_code=200, headers={}) + self.assertIsInstance(dict_response.data, dict) + + # List data + list_response = ApiResponse(data=[1, 2, 3], status_code=200, headers={}) + self.assertIsInstance(list_response.data, list) + + # Boolean data + bool_response = ApiResponse(data=True, status_code=204, headers={}) + self.assertIsInstance(bool_response.data, bool) + + # None data + none_response = ApiResponse(data=None, status_code=204, headers={}) + self.assertIsNone(none_response.data) + + +if __name__ == "__main__": + unittest.main() 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 2f65cab70b..9a74139d40 100644 --- a/tests/unit/http/test_http_client.py +++ b/tests/unit/http/test_http_client.py @@ -1,22 +1,27 @@ # -*- 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.exceptions import TwilioRestException +from twilio.base.version import Version from twilio.http.http_client import TwilioHttpClient from twilio.http.response import Response +from twilio.http.request import Request 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() @@ -28,126 +33,227 @@ def tearDown(self): self.session_patcher.stop() def test_request_sets_host_header_if_missing(self): - self.request_mock.url = 'https://api.twilio.com/' - self.request_mock.headers = {'Host': 'other.twilio.com'} + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} - self.client.request('doesnt matter', 'doesnt matter') + self.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 = """{ + "code": 20001, + "message": "Bad request", + "more_info": "https://www.twilio.com/docs/errors/20001", + "status": 400, + "details": { + "foo":"bar" + } + }""" + self.session_mock.send.return_value = Response(400, error_text) + try: + v1.fetch("get", "none", None, None, None, None, None) + self.fail("should not happen") + except TwilioRestException as err: + self.assertEqual(400, err.status) + self.assertEqual(20001, err.code) + self.assertEqual("get", err.method) + self.assertEqual("Unable to fetch record: Bad request", err.msg) + self.assertEqual({"foo": "bar"}, err.details) class TestHttpClientSession(unittest.TestCase): - def setUp(self): - self.session_patcher = patch('twilio.http.http_client.Session') + self.session_patcher = patch("twilio.http.http_client.Session") self.session_constructor_mock = self.session_patcher.start() def tearDown(self): @@ -155,34 +261,77 @@ 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 TestTwilioRequest(unittest.TestCase): + def test_str(self): + + req = Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts.json", + auth=("AC123", "token"), + params={"PageSize": "1"}, + data={"FriendlyName": "My New Account"}, + headers={"X-Custom-Header": "Value"}, + ) + expected = ( + "POST https://api.twilio.com/2010-04-01/Accounts.json?PageSize=1\n" + ' -d "FriendlyName=My New Account"\n' + ' -H "X-Custom-Header: Value"' + ) + self.assertEqual(expected, req.__str__()) + + def test_str_excludes_authorization_header(self): + req = Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts.json", + params={"PageSize": "1"}, + data={"FriendlyName": "My New Account"}, + headers={ + "Authorization": "Bearer secret-token", + "X-Custom-Header": "Value", + }, + ) + expected = ( + "POST https://api.twilio.com/2010-04-01/Accounts.json?PageSize=1\n" + ' -d "FriendlyName=My New Account"\n' + ' -H "X-Custom-Header: Value"' + ) + self.assertEqual(expected, req.__str__()) + + +class MyVersion(Version): + def __init__(self, domain): + super().__init__(domain, "v1") + self._credentials = None diff --git a/tests/unit/http/test_validation_client.py b/tests/unit/http/test_validation_client.py index 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 5600505718..f2e2affc02 100644 --- a/tests/unit/rest/test_client.py +++ b/tests/unit/rest/test_client.py @@ -1,46 +1,144 @@ import unittest -from twilio.rest import ( - TwilioClient, - TwilioRestClient, - TwilioIpMessagingClient, - TwilioLookupsClient, - TwilioMonitorClient, - TwilioPricingClient, - TwilioTaskRouterClient, - TwilioTrunkingClient, -) -from twilio.base.obsolete import ObsoleteException - - -class TestDummyClients(unittest.TestCase): - def test_obsolete_exception_twilioclient(self): - self.assertRaises(ObsoleteException, TwilioClient, - "Expected raised ObsoleteException") - - def test_obsolete_exception_twiliorestclient(self): - self.assertRaises(ObsoleteException, TwilioRestClient, - "Expected raised ObsoleteException") - - def test_obsolete_exception_twilioipmessagingclient(self): - self.assertRaises(ObsoleteException, TwilioIpMessagingClient, - "Expected raised ObsoleteException") - - def test_obsolete_exception_twiliolookupsclient(self): - self.assertRaises(ObsoleteException, TwilioLookupsClient, - "Expected raised ObsoleteException") - - def test_obsolete_exception_twiliomonitorclient(self): - self.assertRaises(ObsoleteException, TwilioMonitorClient, - "Expected raised ObsoleteException") - - def test_obsolete_exception_twiliopricingclient(self): - self.assertRaises(ObsoleteException, TwilioPricingClient, - "Expected raised ObsoleteException") - - def test_obsolete_exception_twiliotaskrouterclient(self): - self.assertRaises(ObsoleteException, TwilioTaskRouterClient, - "Expected raised ObsoleteException") - - def test_obsolete_exception_twiliotrunkingclient(self): - self.assertRaises(ObsoleteException, TwilioTrunkingClient, - "Expected raised ObsoleteException") + +import aiounittest + +from mock import AsyncMock, Mock + +from twilio.http.response import Response +from twilio.rest import Client + + +class TestRegionEdgeClients(unittest.TestCase): + def setUp(self): + self.client = Client("username", "password") + + def test_set_client_edge_default_region(self): + self.client.edge = "edge" + self.assertEqual( + self.client.get_hostname("https://api.twilio.com"), + "https://api.edge.us1.twilio.com", + ) + + def test_set_client_region(self): + self.client.region = "us1" + self.assertEqual( + self.client.get_hostname("https://api.twilio.com"), + "https://api.us1.twilio.com", + ) + + def test_set_uri_region(self): + self.assertEqual( + self.client.get_hostname("https://api.us1.twilio.com"), + "https://api.us1.twilio.com", + ) + + def test_set_client_edge_region(self): + self.client.edge = "edge" + self.client.region = "region" + self.assertEqual( + self.client.get_hostname("https://api.twilio.com"), + "https://api.edge.region.twilio.com", + ) + + def test_set_client_edge_uri_region(self): + self.client.edge = "edge" + self.assertEqual( + self.client.get_hostname("https://api.region.twilio.com"), + "https://api.edge.region.twilio.com", + ) + + def test_set_client_region_uri_edge_region(self): + self.client.region = "region" + self.assertEqual( + self.client.get_hostname("https://api.edge.uriRegion.twilio.com"), + "https://api.edge.region.twilio.com", + ) + + def test_set_client_edge_uri_edge_region(self): + self.client.edge = "edge" + self.assertEqual( + self.client.get_hostname("https://api.uriEdge.region.twilio.com"), + "https://api.edge.region.twilio.com", + ) + + def test_set_uri_edge_region(self): + self.assertEqual( + self.client.get_hostname("https://api.edge.region.twilio.com"), + "https://api.edge.region.twilio.com", + ) + + def test_periods_in_query(self): + self.client.region = "region" + self.client.edge = "edge" + self.assertEqual( + self.client.get_hostname( + "https://api.twilio.com/path/to/something.json?foo=12.34" + ), + "https://api.edge.region.twilio.com/path/to/something.json?foo=12.34", + ) + + +class TestUserAgentClients(unittest.TestCase): + def setUp(self): + self.client = Client("username", "password") + + def tearDown(self): + self.client.http_client.session.close() + + def test_set_default_user_agent(self): + self.client.request("GET", "https://api.twilio.com/") + request_header = self.client.http_client._test_only_last_request.headers[ + "User-Agent" + ] + self.assertRegex( + request_header, + r"^twilio-python\/[0-9.]+(-rc\.[0-9]+)?\s\(\w+\s\w+\)\sPython\/[^\s]+$", + ) + + def test_set_user_agent_extensions(self): + expected_user_agent_extensions = ["twilio-run/2.0.0-test", "flex-plugin/3.4.0"] + self.client.user_agent_extensions = expected_user_agent_extensions + self.client.request("GET", "https://api.twilio.com/") + user_agent_headers = self.client.http_client._test_only_last_request.headers[ + "User-Agent" + ] + user_agent_extensions = user_agent_headers.split(" ")[ + -len(expected_user_agent_extensions) : + ] + self.assertEqual(user_agent_extensions, expected_user_agent_extensions) + + +class TestClientAsyncRequest(aiounittest.AsyncTestCase): + def setUp(self): + self.mock_async_http_client = AsyncMock() + self.mock_async_http_client.request.return_value = Response(200, "test") + self.mock_async_http_client.is_async = True + self.client = Client( + "username", "password", http_client=self.mock_async_http_client + ) + + async def test_raise_error_if_client_not_marked_async(self): + mock_http_client = Mock() + mock_http_client.request.return_value = Response(200, "doesnt matter") + mock_http_client.is_async = None + + client = Client("username", "password", http_client=mock_http_client) + with self.assertRaises(RuntimeError): + await client.request_async("doesnt matter", "doesnt matter") + + async def test_raise_error_if_client_is_not_async(self): + mock_http_client = Mock() + mock_http_client.request.return_value = Response(200, "doesnt matter") + mock_http_client.is_async = False + + client = Client("username", "password", http_client=mock_http_client) + with self.assertRaises(RuntimeError): + await client.request_async("doesnt matter", "doesnt matter") + + async def test_request_async_called_with_method_and_url(self): + await self.client.request_async("GET", "http://mock.twilio.com") + self.assertEqual(self.mock_async_http_client.request.call_args.args[0], "GET") + self.assertEqual( + self.mock_async_http_client.request.call_args.args[1], + "http://mock.twilio.com", + ) diff --git a/tests/unit/test_request_validator.py b/tests/unit/test_request_validator.py index 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 cee7777c19..f089e67949 100644 --- a/twilio/__init__.py +++ b/twilio/__init__.py @@ -1,3 +1,2 @@ - -__version_info__ = ('6', '38', '0') -__version__ = '.'.join(__version_info__) +__version_info__ = ("9", "10", "9") +__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/api_response.py b/twilio/base/api_response.py new file mode 100644 index 0000000000..4b6ea5969f --- /dev/null +++ b/twilio/base/api_response.py @@ -0,0 +1,51 @@ +""" +ApiResponse class for wrapping API responses with metadata +""" + +from typing import Dict, Generic, TypeVar + +T = TypeVar("T") + + +class ApiResponse(Generic[T]): + """ + Wrapper for API responses that includes HTTP metadata. + + This class is returned by *_with_http_info methods and provides access to: + - The response data (resource instance, list, or boolean) + - HTTP status code + - Response headers + + Attributes: + data: The response data (instance, list, or boolean for delete operations) + status_code: HTTP status code from the response + headers: Dictionary of response headers + + Example: + >>> response = client.accounts.create_with_http_info(friendly_name="Test") + >>> print(response.status_code) # 201 + >>> print(response.headers['Content-Type']) # application/json + >>> account = response.data + >>> print(account.sid) + """ + + def __init__(self, data: T, status_code: int, headers: Dict[str, str]): + """ + Initialize an ApiResponse + + Args: + data: The response payload (instance, list, or boolean) + status_code: HTTP status code (e.g., 200, 201, 204) + headers: Dictionary of response headers + """ + self.data = data + self.status_code = status_code + self.headers = headers + + def __repr__(self) -> str: + """String representation of the ApiResponse""" + return f"ApiResponse(status_code={self.status_code}, data={type(self.data).__name__})" + + def __str__(self) -> str: + """Human-readable string representation""" + return f"" diff --git a/twilio/base/client_base.py b/twilio/base/client_base.py new file mode 100644 index 0000000000..af5ccdb09c --- /dev/null +++ b/twilio/base/client_base.py @@ -0,0 +1,271 @@ +import os +import platform +from typing import Dict, List, MutableMapping, Optional, Tuple +from urllib.parse import urlparse, urlunparse + +from twilio import __version__ +from twilio.http import HttpClient +from twilio.http.http_client import TwilioHttpClient +from twilio.http.response import Response +from twilio.credential.credential_provider import CredentialProvider + + +class ClientBase(object): + """A client for accessing the Twilio API.""" + + def __init__( + self, + username: Optional[str] = None, + password: Optional[str] = None, + account_sid: Optional[str] = None, + region: Optional[str] = None, + http_client: Optional[HttpClient] = None, + environment: Optional[MutableMapping[str, str]] = None, + edge: Optional[str] = None, + user_agent_extensions: Optional[List[str]] = None, + credential_provider: Optional[CredentialProvider] = None, + ): + """ + Initializes the Twilio Client + + :param username: Username to authenticate with + :param password: Password to authenticate with + :param account_sid: Account SID, defaults to Username + :param region: Twilio Region to make requests to, defaults to 'us1' if an edge is provided + :param http_client: HttpClient, defaults to TwilioHttpClient + :param environment: Environment to look for auth details, defaults to os.environ + :param edge: Twilio Edge to make requests to, defaults to None. + :param user_agent_extensions: Additions to the user agent string + :param credential_provider: credential provider for authentication method that needs to be used + """ + + environment = environment or os.environ + + self.username = username or environment.get("TWILIO_ACCOUNT_SID") + """ :type : str """ + self.password = password or environment.get("TWILIO_AUTH_TOKEN") + """ :type : str """ + self.edge = edge or environment.get("TWILIO_EDGE") + """ :type : str """ + self.region = region or environment.get("TWILIO_REGION") + """ :type : str """ + self.user_agent_extensions = user_agent_extensions or [] + """ :type : list[str] """ + self.credential_provider = credential_provider or None + """ :type : CredentialProvider """ + + self.account_sid = account_sid or self.username + """ :type : str """ + self.auth = (self.username, self.password) + """ :type : tuple(str, str) """ + self.http_client: HttpClient = http_client or TwilioHttpClient() + """ :type : HttpClient """ + + def request( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Makes a request to the Twilio API using the configured http client + Authentication information is automatically added if none is provided + + :param method: HTTP Method + :param uri: Fully qualified url + :param params: Query string parameters + :param data: POST body data + :param headers: HTTP Headers + :param auth: Authentication + :param timeout: Timeout in seconds + :param allow_redirects: Should the client follow redirects + + :returns: Response from the Twilio API + """ + headers = self.get_headers(method, headers) + + if self.credential_provider: + + auth_strategy = self.credential_provider.to_auth_strategy() + headers["Authorization"] = auth_strategy.get_auth_string() + elif self.username is not None and self.password is not None: + auth = self.get_auth(auth) + else: + auth = None + + if method == "DELETE": + del headers["Accept"] + + uri = self.get_hostname(uri) + filtered_data = self.copy_non_none_values(data) + return self.http_client.request( + method, + uri, + params=params, + data=filtered_data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + async def request_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Asynchronously makes a request to the Twilio API using the configured http client + The configured http client must be an asynchronous http client + Authentication information is automatically added if none is provided + + :param method: HTTP Method + :param uri: Fully qualified url + :param params: Query string parameters + :param data: POST body data + :param headers: HTTP Headers + :param auth: Authentication + :param timeout: Timeout in seconds + :param allow_redirects: Should the client follow redirects + + :returns: Response from the Twilio API + """ + if not self.http_client.is_async: + raise RuntimeError( + "http_client must be asynchronous to support async API requests" + ) + + headers = self.get_headers(method, headers) + if method == "DELETE": + del headers["Accept"] + + if self.credential_provider: + auth_strategy = self.credential_provider.to_auth_strategy() + headers["Authorization"] = auth_strategy.get_auth_string() + elif self.username is not None and self.password is not None: + auth = self.get_auth(auth) + else: + auth = None + + uri = self.get_hostname(uri) + filtered_data = self.copy_non_none_values(data) + return await self.http_client.request( + method, + uri, + params=params, + data=filtered_data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + def copy_non_none_values(self, data): + if isinstance(data, dict): + return { + k: self.copy_non_none_values(v) + for k, v in data.items() + if v is not None + } + elif isinstance(data, list): + return [ + self.copy_non_none_values(item) for item in data if item is not None + ] + return data + + def get_auth(self, auth: Optional[Tuple[str, str]]) -> Tuple[str, str]: + """ + Get the request authentication object + :param auth: Authentication (username, password) + :returns: The authentication object + """ + return auth or self.auth + + def get_headers( + self, method: str, headers: Optional[Dict[str, str]] + ) -> Dict[str, str]: + """ + Get the request headers including user-agent, extensions, encoding, content-type, MIME type + :param method: HTTP method + :param headers: HTTP headers + :returns: HTTP headers + """ + headers = headers or {} + + # Set User-Agent + pkg_version = __version__ + os_name = platform.system() + os_arch = platform.machine() + python_version = platform.python_version() + headers["User-Agent"] = "twilio-python/{} ({} {}) Python/{}".format( + pkg_version, + os_name, + os_arch, + python_version, + ) + # Extensions + for extension in self.user_agent_extensions: + headers["User-Agent"] += " {}".format(extension) + headers["X-Twilio-Client"] = "python-{}".format(__version__) + + # Types, encodings, etc. + headers["Accept-Charset"] = "utf-8" + if (method == "POST" or method == "PUT") and ("Content-Type" not in headers): + headers["Content-Type"] = "application/x-www-form-urlencoded" + if "Accept" not in headers: + headers["Accept"] = "application/json" + + return headers + + def get_hostname(self, uri: str) -> str: + """ + Determines the proper hostname given edge and region preferences + via client configuration or uri. + + :param uri: Fully qualified url + + :returns: The final uri used to make the request + """ + if not self.edge and not self.region: + return uri + + parsed_url = urlparse(uri) + pieces = parsed_url.netloc.split(".") + prefix = pieces[0] + suffix = ".".join(pieces[-2:]) + region = None + edge = None + if len(pieces) == 4: + # product.region.twilio.com + region = pieces[1] + elif len(pieces) == 5: + # product.edge.region.twilio.com + edge = pieces[1] + region = pieces[2] + + edge = self.edge or edge + region = self.region or region or (edge and "us1") + + parsed_url = parsed_url._replace( + netloc=".".join([part for part in [prefix, edge, region, suffix] if part]) + ) + return str(urlunparse(parsed_url)) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "".format(self.account_sid) diff --git a/twilio/base/deserialize.py b/twilio/base/deserialize.py index ef6370d628..71226c08f8 100644 --- a/twilio/base/deserialize.py +++ b/twilio/base/deserialize.py @@ -1,13 +1,13 @@ import datetime -from decimal import Decimal, BasicContext +from decimal import BasicContext, Decimal from email.utils import parsedate -import pytz +from typing import Optional, Union -ISO8601_DATE_FORMAT = '%Y-%m-%d' -ISO8601_DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ' +ISO8601_DATE_FORMAT = "%Y-%m-%d" +ISO8601_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ" -def iso8601_date(s): +def iso8601_date(s: str) -> Union[datetime.date, str]: """ Parses an ISO 8601 date string and returns a UTC date object or the string if the parsing failed. @@ -15,25 +15,32 @@ def iso8601_date(s): :return: """ try: - return datetime.datetime.strptime(s, ISO8601_DATE_FORMAT).replace(tzinfo=pytz.utc).date() + return ( + datetime.datetime.strptime(s, ISO8601_DATE_FORMAT) + .replace(tzinfo=datetime.timezone.utc) + .date() + ) except (TypeError, ValueError): return s -def iso8601_datetime(s): +def iso8601_datetime( + s: str, +) -> Union[datetime.datetime, str]: """ Parses an ISO 8601 datetime string and returns a UTC datetime object, or the string if parsing failed. :param s: ISO 8601-formatted datetime string (2015-01-25T12:34:56Z) - :return: datetime or str """ try: - return datetime.datetime.strptime(s, ISO8601_DATETIME_FORMAT).replace(tzinfo=pytz.utc) + return datetime.datetime.strptime(s, ISO8601_DATETIME_FORMAT).replace( + tzinfo=datetime.timezone.utc + ) except (TypeError, ValueError): return s -def rfc2822_datetime(s): +def rfc2822_datetime(s: str) -> Optional[datetime.datetime]: """ Parses an RFC 2822 date string and returns a UTC datetime object, or the string if parsing failed. @@ -43,21 +50,20 @@ def rfc2822_datetime(s): date_tuple = parsedate(s) if date_tuple is None: return None - return datetime.datetime(*date_tuple[:6]).replace(tzinfo=pytz.utc) + return datetime.datetime(*date_tuple[:6]).replace(tzinfo=datetime.timezone.utc) -def decimal(d): +def decimal(d: Optional[str]) -> Union[Decimal, str]: """ Parses a decimal string into a Decimal :param d: decimal string - :return: Decimal """ if not d: return d return Decimal(d, BasicContext) -def integer(i): +def integer(i: str) -> Union[int, str]: """ Parses an integer string into an int :param i: integer string diff --git a/twilio/base/domain.py b/twilio/base/domain.py index 459c1dfef3..4f8395ddf2 100644 --- a/twilio/base/domain.py +++ b/twilio/base/domain.py @@ -1,37 +1,48 @@ +from typing import Dict, Optional, Tuple +from twilio.http.response import Response +from twilio.rest import Client + + class Domain(object): """ This represents at Twilio API subdomain. Like, `api.twilio.com` or `lookups.twilio.com'. """ - def __init__(self, twilio): - """ - :param Twilio twilio: - :return: - """ + + def __init__(self, twilio: Client, base_url: str): self.twilio = twilio - self.base_url = None + self.base_url = base_url - def absolute_url(self, uri): + def absolute_url(self, uri: str) -> str: """ Converts a relative `uri` to an absolute url. :param string uri: The relative uri to make absolute. :return: An absolute url (based off this domain) """ - return '{}/{}'.format(self.base_url.strip('/'), uri.strip('/')) + return "{}/{}".format(self.base_url.strip("/"), uri.strip("/")) - def request(self, method, uri, params=None, data=None, headers=None, - auth=None, timeout=None, allow_redirects=False): + def request( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: """ Makes an HTTP request to this domain. - :param string method: The HTTP method. - :param string uri: The HTTP uri. - :param dict params: Query parameters. - :param object data: The request body. - :param dict headers: The HTTP headers. - :param tuple auth: Basic auth tuple of (username, password) - :param int timeout: The request timeout. - :param bool allow_redirects: True if the client should follow HTTP + :param method: The HTTP method. + :param uri: The HTTP uri. + :param params: Query parameters. + :param data: The request body. + :param headers: The HTTP headers. + :param auth: Basic auth tuple of (username, password) + :param timeout: The request timeout. + :param allow_redirects: True if the client should follow HTTP redirects. """ url = self.absolute_url(uri) @@ -43,6 +54,40 @@ def request(self, method, uri, params=None, data=None, headers=None, headers=headers, auth=auth, timeout=timeout, - allow_redirects=allow_redirects + allow_redirects=allow_redirects, ) + async def request_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Makes an asynchronous HTTP request to this domain. + :param method: The HTTP method. + :param uri: The HTTP uri. + :param params: Query parameters. + :param data: The request body. + :param headers: The HTTP headers. + :param auth: Basic auth tuple of (username, password) + :param timeout: The request timeout. + :param allow_redirects: True if the client should follow HTTP + redirects. + """ + url = self.absolute_url(uri) + return await self.twilio.request_async( + method, + url, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) diff --git a/twilio/base/exceptions.py b/twilio/base/exceptions.py index 8e2cf20b48..ad31cbe204 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, List, Dict class TwilioException(Exception): @@ -9,60 +8,212 @@ class TwilioException(Exception): class TwilioRestException(TwilioException): - """ A generic 400 or 500 level exception from the Twilio API + """A generic 400 or 500 level exception from the Twilio API :param int status: the HTTP status that was returned for the exception :param str uri: The URI that caused the exception :param str msg: A human-readable message for the error - :param str method: The HTTP method used to make the request :param int|None code: A Twilio-specific error code for the error. This is not available for all errors. + :param method: The HTTP method used to make the request + :param details: Additional error details returned for the exception """ - def __init__(self, status, uri, msg="", code=None, method='GET'): + def __init__( + self, + status: int, + uri: str, + msg: str = "", + code: Optional[int] = None, + method: str = "GET", + details: Optional[object] = None, + ): self.uri = uri self.status = status self.msg = msg self.code = code self.method = method + self.details = details - def __str__(self): - """ Try to pretty-print the exception, if this is going on screen. """ + def __str__(self) -> str: + """Try to pretty-print the exception, if this is going on screen.""" - def red(words): - return u("\033[31m\033[49m%s\033[0m") % words + def red(words: str) -> str: + return "\033[31m\033[49m%s\033[0m" % words - def white(words): - return u("\033[37m\033[49m%s\033[0m") % words + def white(words: str) -> str: + return "\033[37m\033[49m%s\033[0m" % words - def blue(words): - return u("\033[34m\033[49m%s\033[0m") % words + def blue(words: str) -> str: + return "\033[34m\033[49m%s\033[0m" % words - def teal(words): - return u("\033[36m\033[49m%s\033[0m") % words + def teal(words: str) -> str: + return "\033[36m\033[49m%s\033[0m" % words - def get_uri(code): + def get_uri(code: int) -> str: return "https://www.twilio.com/docs/errors/{0}".format(code) # If it makes sense to print a human readable error message, try to # do it. The one problem is that someone might catch this error and # try to display the message from it to an end user. - if hasattr(sys.stderr, 'isatty') and sys.stderr.isatty(): + if hasattr(sys.stderr, "isatty") and sys.stderr.isatty(): msg = ( "\n{red_error} {request_was}\n\n{http_line}" "\n\n{twilio_returned}\n\n{message}\n".format( red_error=red("HTTP Error"), request_was=white("Your request was:"), http_line=teal("%s %s" % (self.method, self.uri)), - twilio_returned=white( - "Twilio returned the following information:"), - message=blue(str(self.msg)) - )) + twilio_returned=white("Twilio returned the following information:"), + message=blue(str(self.msg)), + ) + ) if self.code: - msg = "".join([msg, "\n{more_info}\n\n{uri}\n\n".format( - more_info=white("More information may be available here:"), - uri=blue(get_uri(self.code))), - ]) + msg = "".join( + [ + msg, + "\n{more_info}\n\n{uri}\n\n".format( + more_info=white("More information may be available here:"), + uri=blue(get_uri(self.code)), + ), + ] + ) return msg else: return "HTTP {0} error: {1}".format(self.status, self.msg) + + +class TwilioServiceException(TwilioException): + """An RFC-9457 compliant exception from a Twilio service + + This exception follows the Problem Details for HTTP APIs specification + (RFC-9457). See https://www.rfc-editor.org/rfc/rfc9457.html + + :param str type: A URI reference that identifies the problem type + :param str title: A short, human-readable summary of the problem type + :param int status: The HTTP status code for this occurrence of the problem + :param int code: Twilio-specific error code + :param str|None detail: A human-readable explanation specific to this occurrence + :param str|None instance: A URI reference identifying the specific occurrence + :param list|None errors: Array of validation errors with detail and pointer fields + :param str method: The HTTP method used to make the request + :param str uri: The URI that caused the exception + """ + + def __init__( + self, + type_uri: str, + title: str, + status: int, + code: int, + detail: Optional[str] = None, + instance: Optional[str] = None, + errors: Optional[List[Dict[str, str]]] = None, + method: str = "GET", + uri: str = "", + ): + self.type = type_uri + self.title = title + self.status = status + self.code = code + self.detail = detail + self.instance = instance + self.errors = errors or [] + self.method = method + self.uri = uri + + def __str__(self) -> str: + """Pretty-print the exception for terminal output.""" + + def red(words: str) -> str: + return "\033[31m\033[49m%s\033[0m" % words + + def white(words: str) -> str: + return "\033[37m\033[49m%s\033[0m" % words + + def blue(words: str) -> str: + return "\033[34m\033[49m%s\033[0m" % words + + def teal(words: str) -> str: + return "\033[36m\033[49m%s\033[0m" % words + + def yellow(words: str) -> str: + return "\033[33m\033[49m%s\033[0m" % words + + # Check if we're in a TTY for colored output + if hasattr(sys.stderr, "isatty") and sys.stderr.isatty(): + msg_parts = [ + "\n{red_error} {request_was}\n\n{http_line}\n\n{twilio_returned}\n".format( + red_error=red("HTTP Error"), + request_was=white("Your request was:"), + http_line=( + teal("%s %s" % (self.method, self.uri)) + if self.uri + else teal("(no URI)") + ), + twilio_returned=white("Twilio returned the following information:"), + ) + ] + + # Title and detail + msg_parts.append( + "\n{title_label}: {title}\n".format( + title_label=white("Title"), + title=blue(self.title), + ) + ) + + if self.detail: + msg_parts.append( + "{detail_label}: {detail}\n".format( + detail_label=white("Detail"), + detail=blue(self.detail), + ) + ) + + # Code and status + msg_parts.append( + "{code_label}: {code} | {status_label}: {status}\n".format( + code_label=white("Error Code"), + code=blue(str(self.code)), + status_label=white("Status"), + status=blue(str(self.status)), + ) + ) + + # Validation errors if present + if self.errors: + msg_parts.append( + "\n{validation_label}:\n".format( + validation_label=white("Validation Errors"), + ) + ) + for error in self.errors: + msg_parts.append( + " {pointer}: {detail}\n".format( + pointer=yellow(error.get("pointer", "(unknown field)")), + detail=error.get("detail", "(no detail)"), + ) + ) + + # Documentation link + msg_parts.append( + "\n{more_info}\n\n{uri}\n\n".format( + more_info=white("More information may be available here:"), + uri=blue(self.type), + ) + ) + + return "".join(msg_parts) + else: + # Plain text output for non-TTY + msg = "HTTP {0} error: {1}".format(self.status, self.title) + if self.detail: + msg += " - {0}".format(self.detail) + if self.errors: + msg += " | Validation errors: {0}".format( + ", ".join( + "{0} ({1})".format(e.get("pointer", "?"), e.get("detail", "?")) + for e in self.errors + ) + ) + return 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/token_pagination.py b/twilio/base/token_pagination.py new file mode 100644 index 0000000000..9631f7e14e --- /dev/null +++ b/twilio/base/token_pagination.py @@ -0,0 +1,154 @@ +from typing import Optional, Any, Dict + +from twilio.base.exceptions import TwilioException +from twilio.base.page import Page + + +class TokenPagination(Page): + """ + Represents a page of records using token-based pagination. + + Token-based pagination uses next_token and previous_token instead of + page numbers to navigate through results. + + Example expected response format with token metadata: + { + "meta": { + "key": "items", + "pageSize": 50, + "nextToken": "abc123", + "previousToken": "xyz789" + }, + "items": [ + { "id": 1, "name": "Item 1" }, + { "id": 2, "name": "Item 2" } + ] + } + """ + + def __init__( + self, + version, + response, + uri: str, + params: Optional[Dict[str, Any]] = None, + solution: Optional[Dict[str, Any]] = None, + ): + super().__init__(version, response, solution) + self._uri = uri + self._params = params if params is not None else {} + + @property + def key(self) -> Optional[str]: + """ + :return str: Returns the key that identifies the collection in the response. + """ + if "meta" in self._payload and "key" in self._payload["meta"]: + return self._payload["meta"]["key"] + return None + + @property + def page_size(self) -> Optional[int]: + """ + :return int: Returns the page size or None if doesn't exist. + """ + if "meta" in self._payload and "pageSize" in self._payload["meta"]: + return self._payload["meta"]["pageSize"] + return None + + @property + def next_token(self) -> Optional[str]: + """ + :return str: Returns the next_token for pagination or None if doesn't exist. + """ + if "meta" in self._payload and "nextToken" in self._payload["meta"]: + return self._payload["meta"]["nextToken"] + return None + + @property + def previous_token(self) -> Optional[str]: + """ + :return str: Returns the previous_token for pagination or None if doesn't exist. + """ + if "meta" in self._payload and "previousToken" in self._payload["meta"]: + return self._payload["meta"]["previousToken"] + return None + + def _get_page(self, token: Optional[str]) -> Optional["TokenPagination"]: + """ + Internal helper to fetch a page using a given token. + + :param token: The pagination token to use. + :return: The page or None if no token exists. + """ + if not token: + return None + + if not self._uri: + raise TwilioException("URI must be provided for token pagination") + + self._params["pageToken"] = token + + response = self._version.page(method="GET", uri=self._uri, params=self._params) + cls = type(self) + return cls(self._version, response, self._uri, self._params, self._solution) + + async def _get_page_async( + self, token: Optional[str] + ) -> Optional["TokenPagination"]: + """ + Internal async helper to fetch a page using a given token. + + :param token: The pagination token to use. + :return: The page or None if no token exists. + """ + if not token: + return None + + if not self._uri: + raise TwilioException("URI must be provided for token pagination") + + # Construct full URL with pageToken parameter + self._params["pageToken"] = token + response = self._version.page(method="GET", uri=self._uri, params=self._params) + cls = type(self) + return cls(self._version, response, self._uri, self._params, self._solution) + + def next_page(self) -> Optional["TokenPagination"]: + """ + Return the next page using token-based pagination. + Makes a request to the same URI with pageToken set to nextToken. + + :return: The next page or None if no next token exists. + """ + return self._get_page(self.next_token) + + async def next_page_async(self) -> Optional["TokenPagination"]: + """ + Asynchronously return the next page using token-based pagination. + Makes a request to the same URI with pageToken set to nextToken. + + :return: The next page or None if no next token exists. + """ + return await self._get_page_async(self.next_token) + + def previous_page(self) -> Optional["TokenPagination"]: + """ + Return the previous page using token-based pagination. + Makes a request to the same URI with pageToken set to previousToken. + + :return: The previous page or None if no previous token exists. + """ + return self._get_page(self.previous_token) + + async def previous_page_async(self) -> Optional["TokenPagination"]: + """ + Asynchronously return the previous page using token-based pagination. + Makes a request to the same URI with pageToken set to previousToken. + + :return: The previous page or None if no previous token exists. + """ + return await self._get_page_async(self.previous_token) + + def __repr__(self) -> str: + return "" diff --git a/twilio/base/values.py b/twilio/base/values.py index f2421c3a7f..16032b1120 100644 --- a/twilio/base/values.py +++ b/twilio/base/values.py @@ -1,12 +1,13 @@ -from six import iteritems +from typing import Dict + unset = object() -def of(d): +def of(d: Dict[str, object]) -> Dict[str, object]: """ Remove unset values from a dict. - :param dict d: A dict to strip. - :return dict: A dict with unset values removed. + :param d: A dict to strip. + :return A dict with unset values removed. """ - return {k: v for k, v in iteritems(d) if v != unset} + return {k: v for k, v in d.items() if v != unset} diff --git a/twilio/base/version.py b/twilio/base/version.py index 51c1bd5da9..61f9261904 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, Union from twilio.base import values -from twilio.base.exceptions import TwilioRestException +from twilio.base.domain import Domain +from twilio.base.exceptions import TwilioRestException, TwilioServiceException +from twilio.base.page import Page +from twilio.http.response import Response class Version(object): @@ -10,28 +13,33 @@ class Version(object): Represents an API version. """ - def __init__(self, domain): - """ - :param Domain domain: - :return: - """ + def __init__(self, domain: Domain, version: str): self.domain = domain - self.version = None + self.version = version - def absolute_url(self, uri): + def absolute_url(self, uri: str) -> str: """ Turns a relative uri into an absolute url. """ return self.domain.absolute_url(self.relative_uri(uri)) - def relative_uri(self, uri): + def relative_uri(self, uri: str) -> str: """ Turns a relative uri into a versioned relative uri. """ - return '{}/{}'.format(self.version.strip('/'), uri.strip('/')) - - def request(self, method, uri, params=None, data=None, headers=None, - auth=None, timeout=None, allow_redirects=False): + return "{}/{}".format(self.version.strip("/"), uri.strip("/")) + + def request( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: """ Make an HTTP request. """ @@ -44,26 +52,99 @@ 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 + ) -> Union[TwilioRestException, TwilioServiceException]: """ - Wraps an exceptional response in a `TwilioRestException`. + Wraps an exceptional response in a `TwilioRestException` or `TwilioServiceException`. + + If the response is RFC-9457 compliant (contains 'type', 'title', 'status', and 'code' fields), + returns a TwilioServiceException. Otherwise, returns a TwilioRestException for backward compatibility. """ # noinspection PyBroadException try: error_payload = json.loads(response.text) - if 'message' in error_payload: - message = '{}: {}'.format(message, error_payload['message']) - code = error_payload.get('code', response.status_code) - return TwilioRestException(response.status_code, uri, message, code, method) + + # Check if this is an RFC-9457 compliant error response + # Required fields: type, title, status, code + if all(key in error_payload for key in ["type", "title", "status", "code"]): + # This is an RFC-9457 compliant error response + return TwilioServiceException( + type_uri=error_payload["type"], + title=error_payload["title"], + status=error_payload["status"], + code=error_payload["code"], + detail=error_payload.get("detail"), + instance=error_payload.get("instance"), + errors=error_payload.get("errors"), + method=method, + uri=uri, + ) + else: + # Legacy error format - use TwilioRestException + if "message" in error_payload: + message = "{}: {}".format(message, error_payload["message"]) + details = error_payload.get("details") + code = error_payload.get("code", response.status_code) + return TwilioRestException( + response.status_code, uri, message, code, method, details + ) except Exception: - return TwilioRestException(response.status_code, uri, message, response.status_code, method) + return TwilioRestException( + response.status_code, uri, message, response.status_code, method + ) + + def _parse_fetch(self, method: str, uri: str, response: Response) -> Any: + """ + Parses fetch response JSON + """ + # Note that 3XX response codes are allowed for fetches. + if response.status_code < 200 or response.status_code >= 400: + raise self.exception(method, uri, response, "Unable to fetch record") + + return json.loads(response.text) - def fetch(self, method, uri, params=None, data=None, headers=None, auth=None, timeout=None, - allow_redirects=False): + def fetch( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: """ Fetch a resource instance. """ @@ -78,13 +159,120 @@ 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 fetch_with_response_info( + 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, + ) -> Tuple[Any, int, Dict[str, str]]: + """ + Fetch a resource and return response metadata + + Returns: + tuple: (payload_dict, status_code, headers_dict) + - payload_dict: The JSON response body as a dictionary + - status_code: HTTP status code (typically 200) + - headers_dict: Response headers as a dictionary + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + payload = self._parse_fetch(method, uri, response) + return payload, response.status_code, dict(response.headers or {}) + + async def fetch_with_response_info_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, + ) -> Tuple[Any, int, Dict[str, str]]: + """ + Asynchronously fetch a resource and return response metadata + + Returns: + tuple: (payload_dict, status_code, headers_dict) + - payload_dict: The JSON response body as a dictionary + - status_code: HTTP status code (typically 200) + - headers_dict: Response headers as a dictionary + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + payload = self._parse_fetch(method, uri, response) + return payload, response.status_code, dict(response.headers or {}) + + def _parse_update(self, method: str, uri: str, response: Response) -> Any: + """ + Parses update response JSON + """ if response.status_code < 200 or response.status_code >= 300: - raise self.exception(method, uri, response, 'Unable to fetch record') + raise self.exception(method, uri, response, "Unable to update record") return json.loads(response.text) - def update(self, method, uri, params=None, data=None, headers=None, auth=None, timeout=None, - allow_redirects=False): + def update( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: """ Update a resource instance. """ @@ -99,13 +287,179 @@ def update(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 update record') + 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 json.loads(response.text) + return self._parse_update(method, uri, response) + + def update_with_response_info( + 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, + ) -> Tuple[Any, int, Dict[str, str]]: + """ + Update a resource and return response metadata - def delete(self, method, uri, params=None, data=None, headers=None, auth=None, timeout=None, - allow_redirects=False): + Returns: + tuple: (payload_dict, status_code, headers_dict) + - payload_dict: The JSON response body as a dictionary + - status_code: HTTP status code (typically 200) + - headers_dict: Response headers as a dictionary + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + payload = self._parse_update(method, uri, response) + return payload, response.status_code, dict(response.headers or {}) + + async def update_with_response_info_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, + ) -> Tuple[Any, int, Dict[str, str]]: + """ + Asynchronously update a resource and return response metadata + + Returns: + tuple: (payload_dict, status_code, headers_dict) + - payload_dict: The JSON response body as a dictionary + - status_code: HTTP status code (typically 200) + - headers_dict: Response headers as a dictionary + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + payload = self._parse_update(method, uri, response) + return payload, response.status_code, dict(response.headers or {}) + + def patch_with_response_info( + 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, + ) -> Tuple[Any, int, Dict[str, str]]: + return self.update_with_response_info( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + async def patch_with_response_info_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, + ) -> Tuple[Any, int, Dict[str, str]]: + return await self.update_with_response_info_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + def _parse_delete(self, method: str, uri: str, response: Response) -> Any: + """ + Parses delete response. Returns response body as dict if present, otherwise True. + + For V1 APIs that return response bodies on delete (e.g., 202 with JSON), + this returns the parsed JSON payload. For traditional deletes (e.g., 204 No Content), + this returns True for backward compatibility. + """ + if response.status_code < 200 or response.status_code >= 300: + raise self.exception(method, uri, response, "Unable to delete record") + + # If response has content, parse and return it (V1 delete with response body) + if response.content and response.text: + try: + return json.loads(response.text) + except (ValueError, json.JSONDecodeError): + # If JSON parsing fails, fall back to boolean + pass + + return ( + True # Traditional delete: if response code is 2XX, deletion was successful + ) + + def delete( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> bool: """ Delete a resource. """ @@ -120,37 +474,133 @@ def delete(self, method, uri, params=None, data=None, headers=None, auth=None, t allow_redirects=allow_redirects, ) - if response.status_code < 200 or response.status_code >= 300: - raise self.exception(method, uri, response, 'Unable to delete record') + return self._parse_delete(method, uri, response) + + async def delete_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> bool: + """ + Asynchronously delete a resource. + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) - return response.status_code == 204 + return self._parse_delete(method, uri, response) + + def delete_with_response_info( + 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, + ) -> Tuple[Union[Dict[str, Any], bool], int, Dict[str, str]]: + """ + Delete a resource and return response metadata + + Returns: + tuple: (payload_or_success, status_code, headers_dict) + - payload_or_success: Response body dict if present (V1 APIs with response body), + or True boolean for traditional deletes (204 No Content) + - status_code: HTTP status code (typically 202 or 204 for successful delete) + - headers_dict: Response headers as a dictionary + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + result = self._parse_delete(method, uri, response) + return result, response.status_code, dict(response.headers or {}) + + async def delete_with_response_info_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, + ) -> Tuple[Union[Dict[str, Any], bool], int, Dict[str, str]]: + """ + Asynchronously delete a resource and return response metadata + + Returns: + tuple: (payload_or_success, status_code, headers_dict) + - payload_or_success: Response body dict if present (V1 APIs with response body), + or True boolean for traditional deletes (204 No Content) + - status_code: HTTP status code (typically 202 or 204 for successful delete) + - headers_dict: Response headers as a dictionary + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + result = self._parse_delete(method, uri, response) + return result, response.status_code, dict(response.headers or {}) - def read_limits(self, limit=None, page_size=None): + def read_limits( + self, limit: Optional[int] = None, page_size: Optional[int] = None + ) -> Dict[str, object]: """ Takes a limit on the max number of records to read and a max page_size and calculates the max number of pages to read. - :param int limit: Max number of records to read. - :param int page_size: Max page size. - :return dict: A dictionary of paging limits. + :param limit: Max number of records to read. + :param page_size: Max page size. + :return A dictionary of paging limits. """ - page_limit = values.unset - - if limit is not None: - - if page_size is None: - page_size = limit - - page_limit = int(ceil(limit / float(page_size))) + if limit is not None and page_size is None: + page_size = limit return { - 'limit': limit or values.unset, - 'page_size': page_size or values.unset, - 'page_limit': page_limit, + "limit": limit or values.unset, + "page_size": page_size or values.unset, } - def page(self, method, uri, params=None, data=None, headers=None, auth=None, timeout=None, - allow_redirects=False): + def page( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: """ Makes an HTTP request. """ @@ -165,13 +615,107 @@ 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 page_with_response_info( + 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, + ) -> Tuple[Response, int, Dict[str, str]]: + """ + Fetch a page and return response metadata + + Returns: + tuple: (response_object, status_code, headers_dict) + - response_object: The Response object (not parsed JSON) + - status_code: HTTP status code + - headers_dict: Response headers as a dictionary + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + return response, response.status_code, dict(response.headers or {}) + + async def page_with_response_info_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, + ) -> Tuple[Response, int, Dict[str, str]]: + """ + Asynchronously fetch a page and return response metadata + + Returns: + tuple: (response_object, status_code, headers_dict) + - response_object: The Response object (not parsed JSON) + - status_code: HTTP status code + - headers_dict: Response headers as a dictionary + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + return response, response.status_code, dict(response.headers or {}) + + def stream( + self, + page: Optional[Page], + limit: Optional[int] = None, + page_limit: Optional[int] = None, + ) -> Iterator[Any]: """ Generates records one a time from a page, stopping at prescribed limits. - :param Page page: The page to stream. - :param int limit: The max number of records to read. - :param int page_imit: The max number of pages to read. + :param page: The page to stream. + :param limit: The max number of records to read. + :param page_limit: The max number of pages to read. """ current_record = 1 current_page = 1 @@ -183,14 +727,69 @@ def stream(self, page, limit=None, page_limit=None): if limit and limit is not values.unset and limit < current_record: return - if page_limit and page_limit is not values.unset and page_limit < current_page: + current_page += 1 + if ( + page_limit + and page_limit is not values.unset + and page_limit < current_page + ): return page = page.next_page() + + async def stream_async( + self, + page: Optional[Page], + limit: Optional[int] = None, + page_limit: Optional[int] = None, + ) -> AsyncIterator[Any]: + """ + Generates records one a time from a page, stopping at prescribed limits. + + :param page: The page to stream. + :param limit: The max number of records to read. + :param page_limit: The max number of pages to read. + """ + current_record = 1 + current_page = 1 + + while page is not None: + for record in page: + yield record + current_record += 1 + if limit and limit is not values.unset and limit < current_record: + return + current_page += 1 + if ( + page_limit + and page_limit is not values.unset + and page_limit < current_page + ): + return + + page = await page.next_page_async() + + def _parse_create(self, method: str, uri: str, response: Response) -> Any: + """ + Parse create response JSON + """ + if response.status_code < 200 or response.status_code >= 300: + raise self.exception(method, uri, response, "Unable to create record") + + return json.loads(response.text) - def create(self, method, uri, params=None, data=None, headers=None, auth=None, timeout=None, - allow_redirects=False): + def create( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: """ Create a resource instance. """ @@ -204,8 +803,96 @@ 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) + + 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) + + def create_with_response_info( + 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, + ) -> Tuple[Any, int, Dict[str, str]]: + """ + Create a resource and return response metadata - if response.status_code < 200 or response.status_code >= 300: - raise self.exception(method, uri, response, 'Unable to create record') + Returns: + tuple: (payload_dict, status_code, headers_dict) + - payload_dict: The JSON response body as a dictionary + - status_code: HTTP status code (e.g., 201) + - headers_dict: Response headers as a dictionary + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + payload = self._parse_create(method, uri, response) + return payload, response.status_code, dict(response.headers or {}) + + async def create_with_response_info_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, + ) -> Tuple[Any, int, Dict[str, str]]: + """ + Asynchronously create a resource and return response metadata - return json.loads(response.text) + Returns: + tuple: (payload_dict, status_code, headers_dict) + - payload_dict: The JSON response body as a dictionary + - status_code: HTTP status code (e.g., 201) + - headers_dict: Response headers as a dictionary + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + payload = self._parse_create(method, uri, response) + return payload, response.status_code, dict(response.headers or {}) 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..cec693ed06 --- /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.oauth.v2.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 5d251fd3dd..2f2d363535 100644 --- a/twilio/http/http_client.py +++ b/twilio/http/http_client.py @@ -1,101 +1,119 @@ +import os +import logging +from typing import Dict, Optional, Tuple + from requests import Request, Session, hooks from requests.adapters import HTTPAdapter from twilio.http import HttpClient -from twilio.http.response import Response from twilio.http.request import Request as TwilioRequest -import logging -from twilio.compat import urlencode +from twilio.http.response import Response -_logger = logging.getLogger('twilio.http_client') +_logger = logging.getLogger("twilio.http_client") class TwilioHttpClient(HttpClient): """ General purpose HTTP Client for interacting with the Twilio API """ - def __init__(self, pool_connections=True, request_hooks=None, 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) + 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..c5e406ffd3 --- /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.oauth.v2.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..4aef7017bd 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,39 +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) + 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) + ) - params = '' - if self.params and self.params != self.ANY: - params = '?{}'.format(urlencode(self.params, doseq=True)) + def __str__(self) -> str: + params = "" + if self.params and self.params != Match.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())) + 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 != self.ANY: - headers = '\n{}'.format('\n'.join(' -H "{}: {}"'.format(k, v) - for k, v in self.headers.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() + if k.lower() != "authorization" + ) + ) - return '{auth}{method} {url}{params}{data}{headers}'.format( - auth=auth, + return "{method} {url}{params}{data}{headers}".format( method=self.method, url=self.url, params=params, @@ -73,5 +86,5 @@ def __str__(self): headers=headers, ) - def __repr__(self): + def __repr__(self) -> str: return str(self) diff --git a/twilio/http/response.py b/twilio/http/response.py index a778a8a2d4..af5a3b1706 100644 --- a/twilio/http/response.py +++ b/twilio/http/response.py @@ -1,16 +1,22 @@ -class Response(object): - """ +from typing import Any, Optional + - """ - def __init__(self, status_code, text): +class Response(object): + def __init__( + self, + status_code: int, + text: str, + headers: Optional[Any] = None, + ): self.content = text + self.headers = headers self.cached = False self.status_code = status_code self.ok = self.status_code < 400 @property - def text(self): + def text(self) -> str: return self.content - def __repr__(self): - return 'HTTP {} {}'.format(self.status_code, self.content) + def __repr__(self) -> str: + return "HTTP {} {}".format(self.status_code, self.content) diff --git a/twilio/http/token_manager.py b/twilio/http/token_manager.py new file mode 100644 index 0000000000..28cc731019 --- /dev/null +++ b/twilio/http/token_manager.py @@ -0,0 +1,7 @@ +from twilio.base.version import Version + + +class TokenManager: + + def fetch_access_token(self, version: Version): + pass diff --git a/twilio/http/validation_client.py b/twilio/http/validation_client.py index 78abe1cbbc..4a376c7f4f 100644 --- a/twilio/http/validation_client.py +++ b/twilio/http/validation_client.py @@ -3,20 +3,28 @@ 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 +41,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 +69,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 +106,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 +114,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..c17b548516 100644 --- a/twilio/jwt/__init__.py +++ b/twilio/jwt/__init__.py @@ -1,23 +1,7 @@ -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 +10,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 +44,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 +59,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 +75,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 +95,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 +132,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 579f53e489..fe898b2095 100644 --- a/twilio/rest/__init__.py +++ b/twilio/rest/__init__.py @@ -1,760 +1,787 @@ -# 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.http.http_client import TwilioHttpClient - - -class Client(object): - """ A client for accessing the Twilio API. """ - - def __init__(self, username=None, password=None, account_sid=None, region=None, - http_client=None, environment=None): +from typing import TYPE_CHECKING, Optional + +from twilio.base.client_base import ClientBase + +if TYPE_CHECKING: + from twilio.rest.accounts import Accounts + from twilio.rest.api import Api + from twilio.rest.assistants import Assistants + from twilio.rest.bulkexports import Bulkexports + from twilio.rest.chat import Chat + from twilio.rest.content import Content + from twilio.rest.conversations import Conversations + from twilio.rest.events import Events + from twilio.rest.flex_api import FlexApi + from twilio.rest.frontline_api import FrontlineApi + from twilio.rest.preview_iam import PreviewIam + from twilio.rest.iam import Iam + from twilio.rest.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.knowledge import Knowledge + from twilio.rest.lookups import Lookups + from twilio.rest.marketplace import Marketplace + from twilio.rest.memory import Memory + from twilio.rest.messaging import Messaging + from twilio.rest.monitor import Monitor + from twilio.rest.notify import Notify + from twilio.rest.numbers import Numbers + from twilio.rest.oauth import Oauth + from twilio.rest.preview import Preview + from twilio.rest.pricing import Pricing + from twilio.rest.proxy import Proxy + from twilio.rest.routes import Routes + from twilio.rest.serverless import Serverless + from twilio.rest.studio import Studio + from twilio.rest.supersim import Supersim + from twilio.rest.sync import Sync + from twilio.rest.taskrouter import Taskrouter + from twilio.rest.trunking import Trunking + from twilio.rest.trusthub import Trusthub + from twilio.rest.verify import Verify + from twilio.rest.video import Video + from twilio.rest.voice import Voice + from twilio.rest.wireless import Wireless + from twilio.rest.api.v2010.account.address import AddressList + from twilio.rest.api.v2010.account.application import ApplicationList + from twilio.rest.api.v2010.account.authorized_connect_app import ( + AuthorizedConnectAppList, + ) + from twilio.rest.api.v2010.account.available_phone_number_country import ( + AvailablePhoneNumberCountryList, + ) + from twilio.rest.api.v2010.account.balance import BalanceList + from twilio.rest.api.v2010.account.call import CallList + from twilio.rest.api.v2010.account.conference import ConferenceList + from twilio.rest.api.v2010.account.connect_app import ConnectAppList + from twilio.rest.api.v2010.account.incoming_phone_number import ( + IncomingPhoneNumberList, + ) + from twilio.rest.api.v2010.account.key import KeyList + from twilio.rest.api.v2010.account.new_key import NewKeyList + from twilio.rest.api.v2010.account.message import MessageList + from twilio.rest.api.v2010.account.signing_key import SigningKeyList + from twilio.rest.api.v2010.account.new_signing_key import NewSigningKeyList + from twilio.rest.api.v2010.account.notification import NotificationList + from twilio.rest.api.v2010.account.outgoing_caller_id import OutgoingCallerIdList + from twilio.rest.api.v2010.account.validation_request import ValidationRequestList + from twilio.rest.api.v2010.account.queue import QueueList + from twilio.rest.api.v2010.account.recording import RecordingList + from twilio.rest.api.v2010.account.short_code import ShortCodeList + from twilio.rest.api.v2010.account.sip import SipList + from twilio.rest.api.v2010.account.token import TokenList + from twilio.rest.api.v2010.account.transcription import TranscriptionList + from twilio.rest.api.v2010.account.usage import UsageList + + +class Client(ClientBase): + """A client for accessing the Twilio API.""" + + def __init__( + self, + username=None, + password=None, + account_sid=None, + region=None, + http_client=None, + environment=None, + edge=None, + user_agent_extensions=None, + credential_provider=None, + ): """ Initializes the Twilio Client - :param str username: Username to authenticate with - :param str password: Password to authenticate with - :param str account_sid: Account Sid, defaults to Username - :param str region: Twilio Region to make requests to + :param str username: Username to authenticate with, either account_sid or api_key + :param str password: Password to authenticate with, auth_token (if using account_sid) or api_secret (if using api_key) + :param str account_sid: Account SID, required if using api_key to authenticate. + :param str region: Twilio Region to make requests to, defaults to 'us1' if an edge is provided :param HttpClient http_client: HttpClient, defaults to TwilioHttpClient :param dict environment: Environment to look for auth details, defaults to os.environ + :param str edge: Twilio Edge to make requests to, defaults to None + :param list[str] user_agent_extensions: Additions to the user agent string :returns: Twilio Client :rtype: twilio.rest.Client """ - environment = environment or os.environ - - self.username = username or environment.get('TWILIO_ACCOUNT_SID') - """ :type : str """ - self.password = password or environment.get('TWILIO_AUTH_TOKEN') - """ :type : str """ - self.account_sid = account_sid or self.username - """ :type : str """ - self.region = region - """ :type : str """ - - if not self.username or not self.password: - raise TwilioException("Credentials are required to create a TwilioClient") - - self.auth = (self.username, self.password) - """ :type : tuple(str, str) """ - self.http_client = http_client or TwilioHttpClient() - """ :type : HttpClient """ - - # Domains - self._accounts = None - self._api = None - self._authy = 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' - - if self.region: - head, tail = uri.split('.', 1) - - if not tail.startswith(self.region): - uri = '.'.join([head, self.region, tail]) - - return self.http_client.request( - method, - uri, - params=params, - data=data, - headers=headers, - auth=auth, - timeout=timeout, - allow_redirects=allow_redirects + super().__init__( + username, + password, + account_sid, + region, + http_client, + environment, + edge, + user_agent_extensions, + credential_provider, ) - @property - def accounts(self): + # Domains + self._accounts: Optional["Accounts"] = None + self._api: Optional["Api"] = None + self._assistants: Optional["Assistants"] = None + self._bulkexports: Optional["Bulkexports"] = None + self._chat: Optional["Chat"] = None + self._content: Optional["Content"] = None + self._conversations: Optional["Conversations"] = None + self._events: Optional["Events"] = None + self._flex_api: Optional["FlexApi"] = None + self._frontline_api: Optional["FrontlineApi"] = None + self._preview_iam: Optional["PreviewIam"] = None + self._iam: Optional["Iam"] = None + self._iam: Optional["Iam"] = None + self._insights: Optional["Insights"] = None + self._intelligence: Optional["Intelligence"] = None + self._ip_messaging: Optional["IpMessaging"] = None + self._knowledge: Optional["Knowledge"] = None + self._lookups: Optional["Lookups"] = None + self._marketplace: Optional["Marketplace"] = None + self._memory: Optional["Memory"] = 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 authy(self): + def assistants(self) -> "Assistants": """ - Access the Authy Twilio Domain + Access the Assistants Twilio Domain - :returns: Authy Twilio Domain - :rtype: twilio.rest.authy.Authy + :returns: Assistants Twilio Domain """ - if self._authy is None: - from twilio.rest.authy import Authy - self._authy = Authy(self) - return self._authy + if self._assistants is None: + from twilio.rest.assistants import Assistants + + self._assistants = Assistants(self) + return self._assistants @property - def autopilot(self): + def bulkexports(self) -> "Bulkexports": """ - Access the Autopilot Twilio Domain + Access the Bulkexports Twilio Domain - :returns: Autopilot Twilio Domain - :rtype: twilio.rest.autopilot.Autopilot + :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 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 knowledge(self) -> "Knowledge": + """ + Access the Knowledge Twilio Domain + + :returns: Knowledge Twilio Domain + """ + if self._knowledge is None: + from twilio.rest.knowledge import Knowledge + + self._knowledge = Knowledge(self) + return self._knowledge + + @property + 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 memory(self) -> "Memory": + """ + Access the Memory Twilio Domain + + :returns: Memory Twilio Domain + """ + if self._memory is None: + from twilio.rest.memory import Memory + + self._memory = Memory(self) + return self._memory + + @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..8be121c71e 100644 --- a/twilio/rest/accounts/v1/__init__.py +++ b/twilio/rest/accounts/v1/__init__.py @@ -1,42 +1,91 @@ -# 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.messaging_geopermissions import MessagingGeopermissionsList +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._messaging_geopermissions: Optional[MessagingGeopermissionsList] = 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 messaging_geopermissions(self) -> MessagingGeopermissionsList: + if self._messaging_geopermissions is None: + self._messaging_geopermissions = MessagingGeopermissionsList(self) + return self._messaging_geopermissions + + @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..c60ea48baa --- /dev/null +++ b/twilio/rest/accounts/v1/auth_token_promotion.py @@ -0,0 +1,238 @@ +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.api_response import ApiResponse +from twilio.base.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 update_with_http_info(self) -> ApiResponse: + """ + Update the AuthTokenPromotionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info() + + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the AuthTokenPromotionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self) -> AuthTokenPromotionInstance: + """ + Update the AuthTokenPromotionInstance + + + :returns: The updated AuthTokenPromotionInstance + """ + payload, _, _ = self._update() + return AuthTokenPromotionInstance(self._version, payload) + + def update_with_http_info(self) -> ApiResponse: + """ + Update the AuthTokenPromotionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update() + instance = AuthTokenPromotionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async(self) -> AuthTokenPromotionInstance: + """ + Asynchronous coroutine to update the AuthTokenPromotionInstance + + + :returns: The updated AuthTokenPromotionInstance + """ + payload, _, _ = await self._update_async() + return AuthTokenPromotionInstance(self._version, payload) + + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the AuthTokenPromotionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async() + instance = AuthTokenPromotionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..423b8ed7eb --- /dev/null +++ b/twilio/rest/accounts/v1/bulk_consents.py @@ -0,0 +1,155 @@ +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.api_response import ApiResponse + +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]) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(items=items) + return BulkConsentsInstance(self._version, payload) + + def create_with_http_info(self, items: List[object]) -> ApiResponse: + """ + Create the BulkConsentsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(items=items) + instance = BulkConsentsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, items: List[object]) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(items=items) + return BulkConsentsInstance(self._version, payload) + + async def create_with_http_info_async(self, items: List[object]) -> ApiResponse: + """ + Asynchronously create the BulkConsentsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(items=items) + instance = BulkConsentsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..4ede446a9e --- /dev/null +++ b/twilio/rest/accounts/v1/bulk_contacts.py @@ -0,0 +1,155 @@ +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.api_response import ApiResponse + +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]) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(items=items) + return BulkContactsInstance(self._version, payload) + + def create_with_http_info(self, items: List[object]) -> ApiResponse: + """ + Create the BulkContactsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(items=items) + instance = BulkContactsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, items: List[object]) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(items=items) + return BulkContactsInstance(self._version, payload) + + async def create_with_http_info_async(self, items: List[object]) -> ApiResponse: + """ + Asynchronously create the BulkContactsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(items=items) + instance = BulkContactsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 33290772e9..0c81106aec 100644 --- a/twilio/rest/accounts/v1/credential/aws.py +++ b/twilio/rest/accounts/v1/credential/aws.py @@ -1,394 +1,1066 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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") - def __init__(self, version): + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[AwsContext] = None + + @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. + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AwsInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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: 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AwsInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists AwsInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AwsInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.accounts.v1.credential.aws.AwsInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "AwsInstance": """ - Retrieve a single page of AwsInstance records from the API. - Request is executed immediately + 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 + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AwsInstance": """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Asynchronous coroutine to fetch the AwsInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return AwsPage(self._version, response, self._solution) + :returns: The fetched AwsInstance + """ + return await self._proxy.fetch_async() - def get_page(self, target_url): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a specific page of AwsInstance records from the API. - Request is executed immediately + Fetch the AwsInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsPage + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AwsInstance with HTTP info - return AwsPage(self._version, response, self._solution) - def create(self, credentials, friendly_name=values.unset, - account_sid=values.unset): + :returns: ApiResponse with instance, status code, and headers """ - Create the AwsInstance + return await self._proxy.fetch_with_http_info_async() + + def update(self, friendly_name: Union[str, object] = values.unset) -> "AwsInstance": + """ + Update the AwsInstance - :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. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: The created AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance + :returns: The updated AwsInstance """ - data = values.of({ - 'Credentials': credentials, - 'FriendlyName': friendly_name, - 'AccountSid': account_sid, - }) + return self._proxy.update( + friendly_name=friendly_name, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "AwsInstance": + """ + Asynchronous coroutine to update the AwsInstance - return AwsInstance(self._version, payload, ) + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - def get(self, sid): + :returns: The updated AwsInstance """ - Constructs a AwsContext + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - :param sid: The unique string that identifies the resource + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the AwsInstance with HTTP info - :returns: twilio.rest.accounts.v1.credential.aws.AwsContext - :rtype: twilio.rest.accounts.v1.credential.aws.AwsContext + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers """ - return AwsContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: """ - Constructs a AwsContext + Asynchronous coroutine to update the AwsInstance with HTTP info - :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.accounts.v1.credential.aws.AwsContext - :rtype: twilio.rest.accounts.v1.credential.aws.AwsContext + :returns: ApiResponse with instance, status code, and headers """ - return AwsContext(self._version, sid=sid, ) + return await self._proxy.update_with_http_info_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 AwsPage(Page): - """ """ +class AwsContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the AwsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the AwsContext - :returns: twilio.rest.accounts.v1.credential.aws.AwsPage - :rtype: twilio.rest.accounts.v1.credential.aws.AwsPage + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the AWS resource to update. """ - super(AwsPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/AWS/{sid}".format(**self._solution) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of AwsInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.accounts.v1.credential.aws.AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance + def delete(self) -> bool: """ - return AwsInstance(self._version, payload, ) + Deletes the AwsInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the AwsInstance and return response metadata -class AwsContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the AwsContext - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource + headers = values.of({}) - :returns: twilio.rest.accounts.v1.credential.aws.AwsContext - :rtype: twilio.rest.accounts.v1.credential.aws.AwsContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(AwsContext, self).__init__(version) + Asynchronous coroutine that deletes the AwsInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/AWS/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AwsInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AwsInstance: """ Fetch the AwsInstance + + :returns: The fetched AwsInstance + """ + payload, _, _ = self._fetch() + return AwsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AwsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AwsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AwsInstance: + """ + Asynchronous coroutine to fetch the AwsInstance + + :returns: The fetched AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = await self._fetch_async() + return AwsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AwsInstance and return response metadata - return AwsInstance(self._version, payload, sid=self._solution['sid'], ) - def update(self, friendly_name=values.unset): + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AwsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, friendly_name: Union[str, object] = values.unset) -> AwsInstance: """ 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._update(friendly_name=friendly_name) + return AwsInstance(self._version, payload, sid=self._solution["sid"]) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the AwsInstance and return response metadata - return AwsInstance(self._version, payload, sid=self._solution['sid'], ) + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - def delete(self): + :returns: ApiResponse with instance, status code, and headers """ - Deletes the AwsInstance + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = AwsInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> AwsInstance: + """ + Asynchronous coroutine to update the AwsInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated AwsInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) + return AwsInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AwsInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = AwsInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 AwsInstance(InstanceResource): - """ """ +class AwsPage(Page): - def __init__(self, version, payload, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> AwsInstance: """ - Initialize the AwsInstance + Build an instance of AwsInstance - :returns: twilio.rest.accounts.v1.credential.aws.AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance + :param payload: Payload response from the API """ - super(AwsInstance, 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'), - } + return AwsInstance(self._version, payload) - # Context - self._context = None - self._solution = {'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: AwsContext for this AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsContext + +class AwsList(ListResource): + + def __init__(self, version: Version): """ - if self._context is None: - self._context = AwsContext(self._version, sid=self._solution['sid'], ) - return self._context + Initialize the AwsList + + :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/AWS" + + def _create( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> tuple: """ - return self._properties['sid'] + Internal helper for create operation - @property - def account_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the Account that created 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> AwsInstance: """ - return self._properties['account_sid'] + Create the AwsInstance - @property - def friendly_name(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 string that you assigned to describe the resource - :rtype: unicode + payload, _, _ = self._create( + credentials=credentials, + friendly_name=friendly_name, + account_sid=account_sid, + ) + return AwsInstance(self._version, payload) + + def create_with_http_info( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['friendly_name'] + Create the AwsInstance and return response metadata - @property - def date_created(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: ApiResponse with instance, status code, and headers """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + payload, status_code, headers = self._create( + credentials=credentials, + friendly_name=friendly_name, + account_sid=account_sid, + ) + instance = AwsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> tuple: """ - return self._properties['date_created'] + Internal async helper for create operation - @property - def date_updated(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> AwsInstance: """ - return self._properties['date_updated'] + Asynchronously create the AwsInstance - @property - def url(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 URI for this resource, relative to `https://accounts.twilio.com` - :rtype: unicode + payload, _, _ = await self._create_async( + credentials=credentials, + friendly_name=friendly_name, + account_sid=account_sid, + ) + return AwsInstance(self._version, payload) + + async def create_with_http_info_async( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['url'] + Asynchronously create the AwsInstance and return response metadata + + :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. - def fetch(self): + :returns: ApiResponse with instance, status code, and headers """ - Fetch the AwsInstance + payload, status_code, headers = await self._create_async( + credentials=credentials, + friendly_name=friendly_name, + account_sid=account_sid, + ) + instance = AwsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AwsInstance]: + """ + Streams AwsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :returns: The fetched AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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"]) - def update(self, friendly_name=values.unset): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AwsInstance]: """ - Update the AwsInstance + Asynchronously streams AwsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :param unicode friendly_name: A string to describe 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: The updated AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance + :returns: Generator that will yield up to limit results """ - return self._proxy.update(friendly_name=friendly_name, ) + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - def delete(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Deletes the AwsInstance + Streams AwsInstance and returns headers from first page - :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._proxy.delete() + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AwsInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AwsInstance]: + """ + Lists AwsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AwsInstance]: + """ + Asynchronously lists AwsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AwsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AwsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AwsPage: + """ + Retrieve a single page of AwsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AwsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AwsPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AwsPage: + """ + Asynchronously retrieve a single page of AwsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AwsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AwsPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AwsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AwsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AwsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AwsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> AwsPage: + """ + Retrieve a specific page of AwsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AwsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AwsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AwsPage: + """ + Asynchronously retrieve a specific page of AwsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AwsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AwsPage(self._version, response) + + def get(self, sid: str) -> AwsContext: + """ + Constructs a AwsContext + + :param sid: The Twilio-provided string that uniquely identifies the AWS resource to update. + """ + return AwsContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AwsContext: + """ + Constructs a AwsContext + + :param sid: The Twilio-provided string that uniquely identifies the AWS resource to update. + """ + return AwsContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 a21ff63d13..1e5333fe17 100644 --- a/twilio/rest/accounts/v1/credential/public_key.py +++ b/twilio/rest/accounts/v1/credential/public_key.py @@ -1,394 +1,1062 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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") - def __init__(self, version): + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[PublicKeyContext] = None + + @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. + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PublicKeyInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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: 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PublicKeyInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists PublicKeyInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PublicKeyInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "PublicKeyInstance": """ - Retrieve a single page of PublicKeyInstance records from the API. - Request is executed immediately + 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 + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PublicKeyInstance": """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Asynchronous coroutine to fetch the PublicKeyInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return PublicKeyPage(self._version, response, self._solution) + :returns: The fetched PublicKeyInstance + """ + return await self._proxy.fetch_async() - def get_page(self, target_url): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a specific page of PublicKeyInstance records from the API. - Request is executed immediately + Fetch the PublicKeyInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyPage + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PublicKeyInstance with HTTP info - return PublicKeyPage(self._version, response, self._solution) - def create(self, public_key, friendly_name=values.unset, - account_sid=values.unset): + :returns: ApiResponse with instance, status code, and headers """ - Create the PublicKeyInstance + return await self._proxy.fetch_with_http_info_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "PublicKeyInstance": + """ + Update the PublicKeyInstance - :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. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: The created PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance + :returns: The updated PublicKeyInstance """ - data = values.of({ - 'PublicKey': public_key, - 'FriendlyName': friendly_name, - 'AccountSid': account_sid, - }) + return self._proxy.update( + friendly_name=friendly_name, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "PublicKeyInstance": + """ + Asynchronous coroutine to update the PublicKeyInstance - return PublicKeyInstance(self._version, payload, ) + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - def get(self, sid): + :returns: The updated PublicKeyInstance """ - Constructs a PublicKeyContext + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - :param sid: The unique string that identifies the resource + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PublicKeyInstance with HTTP info - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers """ - return PublicKeyContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: """ - Constructs a PublicKeyContext + Asynchronous coroutine to update the PublicKeyInstance with HTTP info - :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.accounts.v1.credential.public_key.PublicKeyContext - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext + :returns: ApiResponse with instance, status code, and headers """ - return PublicKeyContext(self._version, sid=sid, ) + return await self._proxy.update_with_http_info_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 PublicKeyPage(Page): - """ """ +class PublicKeyContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the PublicKeyPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the PublicKeyContext - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyPage - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyPage + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the PublicKey resource to update. """ - super(PublicKeyPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/PublicKeys/{sid}".format(**self._solution) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of PublicKeyInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance + def delete(self) -> bool: """ - return PublicKeyInstance(self._version, payload, ) + Deletes the PublicKeyInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the PublicKeyInstance and return response metadata -class PublicKeyContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the PublicKeyContext - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource + headers = values.of({}) - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(PublicKeyContext, self).__init__(version) + Asynchronous coroutine that deletes the PublicKeyInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/PublicKeys/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PublicKeyInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PublicKeyInstance: """ Fetch the PublicKeyInstance + + :returns: The fetched PublicKeyInstance + """ + payload, _, _ = self._fetch() + return PublicKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PublicKeyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PublicKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> PublicKeyInstance: + """ + Asynchronous coroutine to 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, ) + payload, _, _ = await self._fetch_async() + return PublicKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PublicKeyInstance and return response metadata - return PublicKeyInstance(self._version, payload, sid=self._solution['sid'], ) - def update(self, friendly_name=values.unset): + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PublicKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> PublicKeyInstance: """ 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._update(friendly_name=friendly_name) + return PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PublicKeyInstance and return response metadata - return PublicKeyInstance(self._version, payload, sid=self._solution['sid'], ) + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - def delete(self): + :returns: ApiResponse with instance, status code, and headers """ - Deletes the PublicKeyInstance + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> PublicKeyInstance: + """ + Asynchronous coroutine to update the PublicKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated PublicKeyInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) + return PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PublicKeyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 PublicKeyInstance(InstanceResource): - """ """ +class PublicKeyPage(Page): - def __init__(self, version, payload, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> PublicKeyInstance: """ - Initialize the PublicKeyInstance + Build an instance of PublicKeyInstance - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance + :param payload: Payload response from the API """ - super(PublicKeyInstance, 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'), - } + return PublicKeyInstance(self._version, payload) - # Context - self._context = None - self._solution = {'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: PublicKeyContext for this PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext + +class PublicKeyList(ListResource): + + def __init__(self, version: Version): """ - if self._context is None: - self._context = PublicKeyContext(self._version, sid=self._solution['sid'], ) - return self._context + Initialize the PublicKeyList + + :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/PublicKeys" + + def _create( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> tuple: """ - return self._properties['sid'] + Internal helper for create operation - @property - def account_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the Account that created the Credential that the PublicKey resource belongs to - :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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> PublicKeyInstance: """ - return self._properties['account_sid'] + Create the PublicKeyInstance - @property - def friendly_name(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 string that you assigned to describe the resource - :rtype: unicode + payload, _, _ = self._create( + public_key=public_key, friendly_name=friendly_name, account_sid=account_sid + ) + return PublicKeyInstance(self._version, payload) + + def create_with_http_info( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['friendly_name'] + Create the PublicKeyInstance and return response metadata - @property - def date_created(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: ApiResponse with instance, status code, and headers """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + payload, status_code, headers = self._create( + public_key=public_key, friendly_name=friendly_name, account_sid=account_sid + ) + instance = PublicKeyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> tuple: """ - return self._properties['date_created'] + Internal async helper for create operation - @property - def date_updated(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> PublicKeyInstance: """ - return self._properties['date_updated'] + Asynchronously create the PublicKeyInstance - @property - def url(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 URI for this resource, relative to `https://accounts.twilio.com` - :rtype: unicode + payload, _, _ = await self._create_async( + public_key=public_key, friendly_name=friendly_name, account_sid=account_sid + ) + return PublicKeyInstance(self._version, payload) + + async def create_with_http_info_async( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['url'] + Asynchronously create the PublicKeyInstance and return response metadata + + :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 - def fetch(self): + :returns: ApiResponse with instance, status code, and headers """ - Fetch the PublicKeyInstance + payload, status_code, headers = await self._create_async( + public_key=public_key, friendly_name=friendly_name, account_sid=account_sid + ) + instance = PublicKeyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PublicKeyInstance]: + """ + Streams PublicKeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :returns: The fetched PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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"]) - def update(self, friendly_name=values.unset): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PublicKeyInstance]: """ - Update the PublicKeyInstance + Asynchronously streams PublicKeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :param unicode friendly_name: A string to describe 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: The updated PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance + :returns: Generator that will yield up to limit results """ - return self._proxy.update(friendly_name=friendly_name, ) + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - def delete(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Deletes the PublicKeyInstance + Streams PublicKeyInstance and returns headers from first page - :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._proxy.delete() + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PublicKeyInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PublicKeyInstance]: + """ + Lists PublicKeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PublicKeyInstance]: + """ + Asynchronously lists PublicKeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PublicKeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PublicKeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PublicKeyPage: + """ + Retrieve a single page of PublicKeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PublicKeyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PublicKeyPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PublicKeyPage: + """ + Asynchronously retrieve a single page of PublicKeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PublicKeyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PublicKeyPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PublicKeyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PublicKeyPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PublicKeyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PublicKeyPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> PublicKeyPage: + """ + Retrieve a specific page of PublicKeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PublicKeyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PublicKeyPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PublicKeyPage: + """ + Asynchronously retrieve a specific page of PublicKeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PublicKeyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PublicKeyPage(self._version, response) + + def get(self, sid: str) -> PublicKeyContext: + """ + Constructs a PublicKeyContext + + :param sid: The Twilio-provided string that uniquely identifies the PublicKey resource to update. + """ + return PublicKeyContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PublicKeyContext: + """ + Constructs a PublicKeyContext + + :param sid: The Twilio-provided string that uniquely identifies the PublicKey resource to update. + """ + return PublicKeyContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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/messaging_geopermissions.py b/twilio/rest/accounts/v1/messaging_geopermissions.py new file mode 100644 index 0000000000..0d077f885b --- /dev/null +++ b/twilio/rest/accounts/v1/messaging_geopermissions.py @@ -0,0 +1,261 @@ +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, Union +from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class MessagingGeopermissionsInstance(InstanceResource): + """ + :ivar permissions: A list of objects where each object represents the result of processing a messaging Geo Permission. Each object contains the following fields: `country_code`, the country code of the country for which the permission was updated; `type`, the type of the permission i.e. country; `enabled`, true if the permission is enabled else false; `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.permissions: Optional[Dict[str, object]] = payload.get("permissions") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class MessagingGeopermissionsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the MessagingGeopermissionsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Messaging/GeoPermissions" + + def _fetch(self, country_code: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "CountryCode": country_code, + } + ) + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers, params=params + ) + + def fetch( + self, country_code: Union[str, object] = values.unset + ) -> MessagingGeopermissionsInstance: + """ + Fetch the MessagingGeopermissionsInstance + + :param country_code: The country code to filter the geo permissions. If provided, only the geo permission for the specified country will be returned. + :returns: The fetched MessagingGeopermissionsInstance + """ + payload, _, _ = self._fetch(country_code=country_code) + return MessagingGeopermissionsInstance(self._version, payload) + + def fetch_with_http_info( + self, country_code: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the MessagingGeopermissionsInstance and return response metadata + + :param country_code: The country code to filter the geo permissions. If provided, only the geo permission for the specified country will be returned. + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(country_code=country_code) + instance = MessagingGeopermissionsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, country_code: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "CountryCode": country_code, + } + ) + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + async def fetch_async( + self, country_code: Union[str, object] = values.unset + ) -> MessagingGeopermissionsInstance: + """ + Asynchronously fetch the MessagingGeopermissionsInstance + + :param country_code: The country code to filter the geo permissions. If provided, only the geo permission for the specified country will be returned. + :returns: The fetched MessagingGeopermissionsInstance + """ + payload, _, _ = await self._fetch_async(country_code=country_code) + return MessagingGeopermissionsInstance(self._version, payload) + + async def fetch_with_http_info_async( + self, country_code: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously fetch the MessagingGeopermissionsInstance and return response metadata + + :param country_code: The country code to filter the geo permissions. If provided, only the geo permission for the specified country will be returned. + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + country_code=country_code + ) + instance = MessagingGeopermissionsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, permissions: List[object]) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Permissions": serialize.map( + permissions, 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" + + return self._version.update_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def update(self, permissions: List[object]) -> MessagingGeopermissionsInstance: + """ + Update the MessagingGeopermissionsInstance + + :param permissions: A list of objects where each object represents the Geo Permission to be updated. Each object contains the following fields: `country_code`, unique code for each country of Geo Permission; `type`, permission type of the Geo Permission i.e. country; `enabled`, configure true for enabling the Geo Permission, false for disabling the Geo Permission. + + :returns: The updated MessagingGeopermissionsInstance + """ + payload, _, _ = self._update(permissions=permissions) + return MessagingGeopermissionsInstance(self._version, payload) + + def update_with_http_info(self, permissions: List[object]) -> ApiResponse: + """ + Update the MessagingGeopermissionsInstance and return response metadata + + :param permissions: A list of objects where each object represents the Geo Permission to be updated. Each object contains the following fields: `country_code`, unique code for each country of Geo Permission; `type`, permission type of the Geo Permission i.e. country; `enabled`, configure true for enabling the Geo Permission, false for disabling the Geo Permission. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(permissions=permissions) + instance = MessagingGeopermissionsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, permissions: List[object]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Permissions": serialize.map( + permissions, 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" + + return await self._version.update_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, permissions: List[object] + ) -> MessagingGeopermissionsInstance: + """ + Asynchronously update the MessagingGeopermissionsInstance + + :param permissions: A list of objects where each object represents the Geo Permission to be updated. Each object contains the following fields: `country_code`, unique code for each country of Geo Permission; `type`, permission type of the Geo Permission i.e. country; `enabled`, configure true for enabling the Geo Permission, false for disabling the Geo Permission. + + :returns: The updated MessagingGeopermissionsInstance + """ + payload, _, _ = await self._update_async(permissions=permissions) + return MessagingGeopermissionsInstance(self._version, payload) + + async def update_with_http_info_async( + self, permissions: List[object] + ) -> ApiResponse: + """ + Asynchronously update the MessagingGeopermissionsInstance and return response metadata + + :param permissions: A list of objects where each object represents the Geo Permission to be updated. Each object contains the following fields: `country_code`, unique code for each country of Geo Permission; `type`, permission type of the Geo Permission i.e. country; `enabled`, configure true for enabling the Geo Permission, false for disabling the Geo Permission. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + permissions=permissions + ) + instance = MessagingGeopermissionsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/accounts/v1/safelist.py b/twilio/rest/accounts/v1/safelist.py new file mode 100644 index 0000000000..f7e7912dde --- /dev/null +++ b/twilio/rest/accounts/v1/safelist.py @@ -0,0 +1,341 @@ +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.api_response import ApiResponse + +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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(phone_number=phone_number) + return SafelistInstance(self._version, payload) + + def create_with_http_info(self, phone_number: str) -> ApiResponse: + """ + Create the SafelistInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(phone_number=phone_number) + instance = SafelistInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, phone_number: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(phone_number=phone_number) + return SafelistInstance(self._version, payload) + + async def create_with_http_info_async(self, phone_number: str) -> ApiResponse: + """ + Asynchronously create the SafelistInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number + ) + instance = SafelistInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _delete(self, phone_number: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + params = values.of( + { + "PhoneNumber": phone_number, + } + ) + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers, params=params + ) + + def delete(self, phone_number: Union[str, object] = values.unset) -> bool: + """ + 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 + """ + success, _, _ = self._delete(phone_number=phone_number) + return success + + def delete_with_http_info( + self, phone_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Delete the SafelistInstance and return response metadata + + :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: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(phone_number=phone_number) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, phone_number: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + params = values.of( + { + "PhoneNumber": phone_number, + } + ) + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async(phone_number=phone_number) + return success + + async def delete_with_http_info_async( + self, phone_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously delete the SafelistInstance and return response metadata + + :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: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + phone_number=phone_number + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self, phone_number: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "PhoneNumber": phone_number, + } + ) + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers, params=params + ) + + def fetch( + self, phone_number: Union[str, object] = values.unset + ) -> SafelistInstance: + """ + 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 + """ + payload, _, _ = self._fetch(phone_number=phone_number) + return SafelistInstance(self._version, payload) + + def fetch_with_http_info( + self, phone_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the SafelistInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(phone_number=phone_number) + instance = SafelistInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, phone_number: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "PhoneNumber": phone_number, + } + ) + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + 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 + """ + payload, _, _ = await self._fetch_async(phone_number=phone_number) + return SafelistInstance(self._version, payload) + + async def fetch_with_http_info_async( + self, phone_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously fetch the SafelistInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + phone_number=phone_number + ) + instance = SafelistInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..9d79a739d7 --- /dev/null +++ b/twilio/rest/accounts/v1/secondary_auth_token.py @@ -0,0 +1,342 @@ +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.api_response import ApiResponse +from twilio.base.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 create_with_http_info(self) -> ApiResponse: + """ + Create the SecondaryAuthTokenInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info() + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the SecondaryAuthTokenInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SecondaryAuthTokenInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SecondaryAuthTokenInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self) -> SecondaryAuthTokenInstance: + """ + Create the SecondaryAuthTokenInstance + + + :returns: The created SecondaryAuthTokenInstance + """ + payload, _, _ = self._create() + return SecondaryAuthTokenInstance(self._version, payload) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the SecondaryAuthTokenInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = SecondaryAuthTokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self) -> SecondaryAuthTokenInstance: + """ + Asynchronous coroutine to create the SecondaryAuthTokenInstance + + + :returns: The created SecondaryAuthTokenInstance + """ + payload, _, _ = await self._create_async() + return SecondaryAuthTokenInstance(self._version, payload) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the SecondaryAuthTokenInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = SecondaryAuthTokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the SecondaryAuthTokenInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SecondaryAuthTokenInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SecondaryAuthTokenInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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 d931c32ff8..0aa9ecd0b0 100644 --- a/twilio/rest/api/v2010/account/__init__.py +++ b/twilio/rest/api/v2010/account/__init__.py @@ -1,21 +1,34 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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 +51,1509 @@ from twilio.rest.api.v2010.account.validation_request import ValidationRequestList -class AccountList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the AccountList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.api.v2010.account.AccountList - :rtype: twilio.rest.api.v2010.account.AccountList - """ - super(AccountList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Accounts.json'.format(**self._solution) - - def create(self, friendly_name=values.unset): - """ - Create the AccountInstance - - :param unicode friendly_name: A human readable description of the account - - :returns: The created AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance - """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return AccountInstance(self._version, payload, ) - - def stream(self, friendly_name=values.unset, status=values.unset, limit=None, - page_size=None): - """ - 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) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.AccountInstance] - """ - limits = self._version.read_limits(limit, page_size) +class AccountInstance(InstanceResource): - page = self.page(friendly_name=friendly_name, status=status, page_size=limits['page_size'], ) + class Status(object): + ACTIVE = "active" + SUSPENDED = "suspended" + CLOSED = "closed" - return self._version.stream(page, limits['limit'], limits['page_limit']) + class Type(object): + TRIAL = "Trial" + FULL = "Full" - def list(self, friendly_name=values.unset, status=values.unset, limit=None, - page_size=None): - """ - Lists AccountInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + """ + :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") - :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) + self._solution = { + "sid": sid or self.sid, + } - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.AccountInstance] - """ - return list(self.stream( - friendly_name=friendly_name, - status=status, - limit=limit, - page_size=page_size, - )) + self._context: Optional[AccountContext] = None - def page(self, friendly_name=values.unset, status=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + @property + def _proxy(self) -> "AccountContext": """ - Retrieve a single page of AccountInstance records from the API. - Request is executed immediately - - :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 + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Page of AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountPage + :returns: AccountContext for this AccountInstance """ - data = values.of({ - '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 AccountPage(self._version, response, self._solution) + if self._context is None: + self._context = AccountContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def get_page(self, target_url): + def fetch(self) -> "AccountInstance": """ - Retrieve a specific page of AccountInstance records from the API. - Request is executed immediately + Fetch the AccountInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountPage + :returns: The fetched AccountInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return AccountPage(self._version, response, self._solution) + return self._proxy.fetch() - def get(self, sid): + async def fetch_async(self) -> "AccountInstance": """ - Constructs a AccountContext - - :param sid: Fetch by unique Account Sid + Asynchronous coroutine to fetch the AccountInstance - :returns: twilio.rest.api.v2010.account.AccountContext - :rtype: twilio.rest.api.v2010.account.AccountContext - """ - return AccountContext(self._version, sid=sid, ) - def __call__(self, sid): + :returns: The fetched AccountInstance """ - Constructs a AccountContext - - :param sid: Fetch by unique Account Sid + return await self._proxy.fetch_async() - :returns: twilio.rest.api.v2010.account.AccountContext - :rtype: twilio.rest.api.v2010.account.AccountContext + def fetch_with_http_info(self) -> ApiResponse: """ - return AccountContext(self._version, sid=sid, ) + Fetch the AccountInstance with HTTP info - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: ApiResponse with instance, status code, and headers """ - return '' - + return self._proxy.fetch_with_http_info() -class AccountPage(Page): - """ """ - - def __init__(self, version, response, solution): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Initialize the AccountPage + Asynchronous coroutine to fetch the AccountInstance with HTTP info - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.api.v2010.account.AccountPage - :rtype: twilio.rest.api.v2010.account.AccountPage + :returns: ApiResponse with instance, status code, and headers """ - super(AccountPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return await self._proxy.fetch_with_http_info_async() - def get_instance(self, payload): + def update( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> "AccountInstance": """ - Build an instance of AccountInstance - - :param dict payload: Payload response from the API + Update the AccountInstance - :returns: twilio.rest.api.v2010.account.AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance - """ - return AccountInstance(self._version, payload, ) + :param friendly_name: Update the human-readable description of this Account + :param status: - def __repr__(self): + :returns: The updated AccountInstance """ - Provide a friendly representation + return self._proxy.update( + friendly_name=friendly_name, + status=status, + ) - :returns: Machine friendly representation - :rtype: str + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> "AccountInstance": """ - return '' + Asynchronous coroutine to update the AccountInstance + :param friendly_name: Update the human-readable description of this Account + :param status: -class AccountContext(InstanceContext): - """ """ - - def __init__(self, version, sid): + :returns: The updated AccountInstance """ - Initialize the AccountContext - - :param Version version: Version that contains the resource - :param sid: Fetch by unique Account Sid + return await self._proxy.update_async( + friendly_name=friendly_name, + status=status, + ) - :returns: twilio.rest.api.v2010.account.AccountContext - :rtype: twilio.rest.api.v2010.account.AccountContext + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> ApiResponse: """ - super(AccountContext, self).__init__(version) + Update the AccountInstance with HTTP info - # 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): - """ - Fetch the AccountInstance + :param friendly_name: Update the human-readable description of this Account + :param status: - :returns: The fetched AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance + :returns: ApiResponse with instance, status code, and headers """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return AccountInstance(self._version, payload, sid=self._solution['sid'], ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + status=status, + ) - def update(self, friendly_name=values.unset, status=values.unset): + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> ApiResponse: """ - Update the AccountInstance + Asynchronous coroutine to update the AccountInstance with HTTP info - :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 - :rtype: twilio.rest.api.v2010.account.AccountInstance + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'FriendlyName': friendly_name, 'Status': status, }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return AccountInstance(self._version, payload, sid=self._solution['sid'], ) + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + status=status, + ) @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'], ) - return self._addresses + return self._proxy.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'], ) - return self._applications + return self._proxy.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'], - ) - return self._authorized_connect_apps + return self._proxy.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'], - ) - return self._available_phone_numbers + return self._proxy.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'], ) - return self._balance + return self._proxy.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'], ) - return self._calls + return self._proxy.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'], ) - return self._conferences + return self._proxy.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'], ) - return self._connect_apps + return self._proxy.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'], - ) - return self._incoming_phone_numbers + return self._proxy.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'], ) - return self._keys + return self._proxy.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'], ) - return self._messages + return self._proxy.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'], ) - return self._new_keys + return self._proxy.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'], ) - return self._new_signing_keys + return self._proxy.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'], ) - return self._notifications + return self._proxy.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'], ) - return self._outgoing_caller_ids + return self._proxy.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'], ) - return self._queues + return self._proxy.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'], ) - return self._recordings + return self._proxy.recordings @property - def signing_keys(self): + def short_codes(self) -> ShortCodeList: """ - Access the signing_keys - - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyList - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyList + Access the short_codes """ - if self._signing_keys is None: - self._signing_keys = SigningKeyList(self._version, account_sid=self._solution['sid'], ) - return self._signing_keys + return self._proxy.short_codes @property - def sip(self): + def signing_keys(self) -> SigningKeyList: """ - Access the sip - - :returns: twilio.rest.api.v2010.account.sip.SipList - :rtype: twilio.rest.api.v2010.account.sip.SipList + Access the signing_keys """ - if self._sip is None: - self._sip = SipList(self._version, account_sid=self._solution['sid'], ) - return self._sip + return self._proxy.signing_keys @property - def short_codes(self): + def sip(self) -> SipList: """ - Access the short_codes - - :returns: twilio.rest.api.v2010.account.short_code.ShortCodeList - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList + Access the sip """ - if self._short_codes is None: - self._short_codes = ShortCodeList(self._version, account_sid=self._solution['sid'], ) - return self._short_codes + return self._proxy.sip @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'], ) - return self._tokens + return self._proxy.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'], ) - return self._transcriptions + return self._proxy.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'], ) - return self._usage + return self._proxy.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'], ) - return self._validation_requests + return self._proxy.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) + 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" +class AccountContext(InstanceContext): - def __init__(self, version, payload, sid=None): + def __init__(self, version: Version, sid: str): """ - Initialize the AccountInstance + Initialize the AccountContext - :returns: twilio.rest.api.v2010.account.AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance + :param version: Version that contains the resource + :param sid: The Account Sid that uniquely identifies the account to update """ - super(AccountInstance, self).__init__(version) + super().__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'), + # Path Solution + self._solution = { + "sid": sid, } + self._uri = "/Accounts/{sid}.json".format(**self._solution) + + self._addresses: Optional[AddressList] = None + self._applications: Optional[ApplicationList] = None + self._authorized_connect_apps: Optional[AuthorizedConnectAppList] = None + self._available_phone_numbers: Optional[AvailablePhoneNumberCountryList] = None + self._balance: Optional[BalanceList] = None + self._calls: Optional[CallList] = None + self._conferences: Optional[ConferenceList] = None + self._connect_apps: Optional[ConnectAppList] = None + self._incoming_phone_numbers: Optional[IncomingPhoneNumberList] = None + self._keys: Optional[KeyList] = None + self._messages: Optional[MessageList] = None + self._new_keys: Optional[NewKeyList] = None + self._new_signing_keys: Optional[NewSigningKeyList] = None + self._notifications: Optional[NotificationList] = None + self._outgoing_caller_ids: Optional[OutgoingCallerIdList] = None + self._queues: Optional[QueueList] = None + self._recordings: Optional[RecordingList] = None + self._short_codes: Optional[ShortCodeList] = None + self._signing_keys: Optional[SigningKeyList] = None + self._sip: Optional[SipList] = None + self._tokens: Optional[TokenList] = None + self._transcriptions: Optional[TranscriptionList] = None + self._usage: Optional[UsageList] = None + self._validation_requests: Optional[ValidationRequestList] = None + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AccountInstance: + """ + Fetch the AccountInstance - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): + :returns: The fetched AccountInstance """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, _, _ = self._fetch() + return AccountInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: AccountContext for this AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountContext + def fetch_with_http_info(self) -> ApiResponse: """ - if self._context is None: - self._context = AccountContext(self._version, sid=self._solution['sid'], ) - return self._context + Fetch the AccountInstance and return response metadata - @property - def auth_token(self): - """ - :returns: The authorization token for this account - :rtype: unicode - """ - return self._properties['auth_token'] - @property - def date_created(self): + :returns: ApiResponse with instance, status code, and headers """ - :returns: The date this account was created - :rtype: datetime - """ - return self._properties['date_created'] + payload, status_code, headers = self._fetch() + instance = AccountInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def date_updated(self): + async def _fetch_async(self) -> tuple: """ - :returns: The date this account was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + Internal async helper for fetch operation - @property - def friendly_name(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: A human readable description of this account - :rtype: unicode - """ - return self._properties['friendly_name'] - @property - def owner_account_sid(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AccountInstance: """ - :returns: The unique 34 character id representing the parent of this account - :rtype: unicode + Asynchronous coroutine to fetch the AccountInstance + + + :returns: The fetched AccountInstance """ - return self._properties['owner_account_sid'] + payload, _, _ = await self._fetch_async() + return AccountInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - @property - def sid(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode + Asynchronous coroutine to fetch the AccountInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['sid'] + payload, status_code, headers = await self._fetch_async() + instance = AccountInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def status(self): + def _update( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> tuple: """ - :returns: The status of this account - :rtype: AccountInstance.Status + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['status'] - @property - def subresource_uris(self): + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> AccountInstance: """ - :returns: Account Instance Subresources - :rtype: unicode + Update the AccountInstance + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: The updated AccountInstance """ - return self._properties['subresource_uris'] + payload, _, _ = self._update(friendly_name=friendly_name, status=status) + return AccountInstance(self._version, payload, sid=self._solution["sid"]) - @property - def type(self): + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> ApiResponse: """ - :returns: The type of this account - :rtype: AccountInstance.Type + Update the AccountInstance and return response metadata + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['type'] + payload, status_code, headers = self._update( + friendly_name=friendly_name, status=status + ) + instance = AccountInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def uri(self): + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> tuple: """ - :returns: The URI for this resource, relative to `https://api.twilio.com` - :rtype: unicode + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['uri'] - def fetch(self): + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> AccountInstance: """ - Fetch the AccountInstance + Asynchronous coroutine to update the AccountInstance - :returns: The fetched AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: The updated AccountInstance """ - return self._proxy.fetch() + payload, _, _ = await self._update_async( + friendly_name=friendly_name, status=status + ) + return AccountInstance(self._version, payload, sid=self._solution["sid"]) - def update(self, friendly_name=values.unset, status=values.unset): + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> ApiResponse: """ - Update the AccountInstance + Asynchronous coroutine to update the AccountInstance and return response metadata - :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 - :rtype: twilio.rest.api.v2010.account.AccountInstance + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.update(friendly_name=friendly_name, status=status, ) + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, status=status + ) + instance = AccountInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 """ - return self._proxy.addresses + if self._addresses is None: + 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 """ - return self._proxy.applications + if self._applications is None: + 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 """ - return self._proxy.authorized_connect_apps + if self._authorized_connect_apps is None: + self._authorized_connect_apps = AuthorizedConnectAppList( + self._version, + self._solution["sid"], + ) + return self._authorized_connect_apps @property - def available_phone_numbers(self): + 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 """ - return self._proxy.available_phone_numbers + if self._available_phone_numbers is None: + self._available_phone_numbers = AvailablePhoneNumberCountryList( + self._version, + self._solution["sid"], + ) + return self._available_phone_numbers @property - def balance(self): + def balance(self) -> BalanceList: """ Access the balance - - :returns: twilio.rest.api.v2010.account.balance.BalanceList - :rtype: twilio.rest.api.v2010.account.balance.BalanceList """ - return self._proxy.balance + if self._balance is None: + 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 """ - return self._proxy.calls + if self._calls is None: + 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 """ - return self._proxy.conferences + if self._conferences is None: + 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 """ - return self._proxy.connect_apps + if self._connect_apps is None: + self._connect_apps = ConnectAppList( + self._version, + self._solution["sid"], + ) + return self._connect_apps @property - def incoming_phone_numbers(self): + 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 """ - return self._proxy.incoming_phone_numbers + if self._incoming_phone_numbers is None: + self._incoming_phone_numbers = IncomingPhoneNumberList( + self._version, + self._solution["sid"], + ) + return self._incoming_phone_numbers @property - def keys(self): + def keys(self) -> KeyList: """ Access the keys - - :returns: twilio.rest.api.v2010.account.key.KeyList - :rtype: twilio.rest.api.v2010.account.key.KeyList """ - return self._proxy.keys + if self._keys is None: + 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 """ - return self._proxy.messages + if self._messages is None: + 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 """ - return self._proxy.new_keys + if self._new_keys is None: + self._new_keys = NewKeyList( + self._version, + self._solution["sid"], + ) + return self._new_keys @property - def new_signing_keys(self): + 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 """ - return self._proxy.new_signing_keys + if self._new_signing_keys is None: + self._new_signing_keys = NewSigningKeyList( + self._version, + self._solution["sid"], + ) + return self._new_signing_keys @property - def notifications(self): + def notifications(self) -> NotificationList: """ Access the notifications - - :returns: twilio.rest.api.v2010.account.notification.NotificationList - :rtype: twilio.rest.api.v2010.account.notification.NotificationList """ - return self._proxy.notifications + if self._notifications is None: + 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 """ - return self._proxy.outgoing_caller_ids + if self._outgoing_caller_ids is None: + self._outgoing_caller_ids = OutgoingCallerIdList( + self._version, + self._solution["sid"], + ) + return self._outgoing_caller_ids @property - def queues(self): + def queues(self) -> QueueList: """ Access the queues - - :returns: twilio.rest.api.v2010.account.queue.QueueList - :rtype: twilio.rest.api.v2010.account.queue.QueueList """ - return self._proxy.queues + if self._queues is None: + self._queues = QueueList( + self._version, + self._solution["sid"], + ) + return self._queues @property - def recordings(self): + def recordings(self) -> RecordingList: """ Access the recordings + """ + if self._recordings is None: + self._recordings = RecordingList( + self._version, + self._solution["sid"], + ) + return self._recordings - :returns: twilio.rest.api.v2010.account.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.recording.RecordingList + @property + def short_codes(self) -> ShortCodeList: """ - return self._proxy.recordings + Access the short_codes + """ + if self._short_codes is None: + self._short_codes = ShortCodeList( + self._version, + self._solution["sid"], + ) + return self._short_codes @property - def signing_keys(self): + def signing_keys(self) -> SigningKeyList: """ Access the signing_keys - - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyList - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyList """ - return self._proxy.signing_keys + if self._signing_keys is None: + self._signing_keys = SigningKeyList( + self._version, + self._solution["sid"], + ) + return self._signing_keys @property - def sip(self): + def sip(self) -> SipList: """ Access the sip + """ + if self._sip is None: + self._sip = SipList( + self._version, + self._solution["sid"], + ) + return self._sip - :returns: twilio.rest.api.v2010.account.sip.SipList - :rtype: twilio.rest.api.v2010.account.sip.SipList + @property + def tokens(self) -> TokenList: """ - return self._proxy.sip + Access the tokens + """ + if self._tokens is None: + self._tokens = TokenList( + self._version, + self._solution["sid"], + ) + return self._tokens @property - def short_codes(self): + def transcriptions(self) -> TranscriptionList: """ - Access the short_codes + Access the transcriptions + """ + if self._transcriptions is None: + self._transcriptions = TranscriptionList( + self._version, + self._solution["sid"], + ) + return self._transcriptions - :returns: twilio.rest.api.v2010.account.short_code.ShortCodeList - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList + @property + def usage(self) -> UsageList: """ - return self._proxy.short_codes + Access the usage + """ + if self._usage is None: + self._usage = UsageList( + self._version, + self._solution["sid"], + ) + return self._usage @property - def tokens(self): + def validation_requests(self) -> ValidationRequestList: """ - Access the tokens + Access the validation_requests + """ + if self._validation_requests is None: + self._validation_requests = ValidationRequestList( + self._version, + self._solution["sid"], + ) + return self._validation_requests - :returns: twilio.rest.api.v2010.account.token.TokenList - :rtype: twilio.rest.api.v2010.account.token.TokenList + def __repr__(self) -> str: """ - return self._proxy.tokens + Provide a friendly representation - @property - def transcriptions(self): + :returns: Machine friendly representation """ - Access the transcriptions + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccountPage(Page): - :returns: twilio.rest.api.v2010.account.transcription.TranscriptionList - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionList + def get_instance(self, payload: Dict[str, Any]) -> AccountInstance: """ - return self._proxy.transcriptions + Build an instance of AccountInstance - @property - def usage(self): + :param payload: Payload response from the API """ - Access the usage - :returns: twilio.rest.api.v2010.account.usage.UsageList - :rtype: twilio.rest.api.v2010.account.usage.UsageList + return AccountInstance(self._version, payload) + + def __repr__(self) -> str: """ - return self._proxy.usage + Provide a friendly representation - @property - def validation_requests(self): + :returns: Machine friendly representation """ - Access the validation_requests + return "" + - :returns: twilio.rest.api.v2010.account.validation_request.ValidationRequestList - :rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestList +class AccountList(ListResource): + + def __init__(self, version: Version): """ - return self._proxy.validation_requests + Initialize the AccountList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Accounts.json" + + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> AccountInstance: + """ + Create the AccountInstance + + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + + :returns: The created AccountInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) + return AccountInstance(self._version, payload) + + def create_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the AccountInstance and return response metadata + + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = AccountInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> AccountInstance: + """ + Asynchronously create the AccountInstance + + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + + :returns: The created AccountInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return AccountInstance(self._version, payload) + + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the AccountInstance and return response metadata + + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = AccountInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AccountInstance]: + """ + Streams AccountInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + friendly_name=friendly_name, status=status, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AccountInstance]: + """ + Asynchronously streams AccountInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, status=status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AccountInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams AccountInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountInstance]: + """ + Lists AccountInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountInstance]: + """ + Asynchronously lists AccountInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AccountInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists AccountInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountPage: + """ + Retrieve a single page of AccountInstance records from the API. + Request is executed immediately + + :param friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountPage(self._version, response) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountPage: + """ + Asynchronously retrieve a single page of AccountInstance records from the API. + Request is executed immediately + + :param friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountPage(self._version, response) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with AccountPage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AccountPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with AccountPage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AccountPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> AccountPage: + """ + Retrieve a specific page of AccountInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AccountPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AccountPage: + """ + Asynchronously retrieve a specific page of AccountInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AccountPage(self._version, response) + + def get(self, sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param sid: The Account Sid that uniquely identifies the account to update + """ + return AccountContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param sid: The Account Sid that uniquely identifies the account to update + """ + return AccountContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 dbafa3a4f6..c309d54844 100644 --- a/twilio/rest/api/v2010/account/address/__init__.py +++ b/twilio/rest/api/v2010/account/address/__init__.py @@ -1,603 +1,1672 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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 delete_with_http_info(self) -> ApiResponse: """ - Streams AddressInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Deletes the AddressInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.delete_with_http_info() - page = self.page( - customer_name=customer_name, - friendly_name=friendly_name, - iso_country=iso_country, - page_size=limits['page_size'], - ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddressInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, customer_name=values.unset, friendly_name=values.unset, - iso_country=values.unset, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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.delete_with_http_info_async() + + def fetch(self) -> "AddressInstance": + """ + 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. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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 """ - return list(self.stream( - customer_name=customer_name, - friendly_name=friendly_name, - iso_country=iso_country, - limit=limit, - page_size=page_size, - )) + return self._proxy.fetch() - 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): + async def fetch_async(self) -> "AddressInstance": """ - Retrieve a single page of AddressInstance records from the API. - Request is executed immediately + Asynchronous coroutine to 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 str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressPage + :returns: The fetched AddressInstance """ - data = values.of({ - 'CustomerName': customer_name, - 'FriendlyName': friendly_name, - 'IsoCountry': iso_country, - '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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AddressInstance with HTTP info - return AddressPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - 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 + return self._proxy.fetch_with_http_info() - :returns: Page of AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressPage + async def fetch_with_http_info_async(self) -> ApiResponse: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronous coroutine to fetch the AddressInstance with HTTP info - return AddressPage(self._version, response, self._solution) - def get(self, sid): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a AddressContext + return await self._proxy.fetch_with_http_info_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 sid: The unique string that identifies the resource + :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: twilio.rest.api.v2010.account.address.AddressContext - :rtype: twilio.rest.api.v2010.account.address.AddressContext + :returns: The updated AddressInstance """ - return AddressContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + 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, + ) - def __call__(self, sid): + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> "AddressInstance": + """ + Asynchronous coroutine to update the AddressInstance + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The updated AddressInstance """ - Constructs a AddressContext + return await self._proxy.update_async( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) - :param sid: The unique string that identifies the resource + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the AddressInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AddressInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) - :returns: twilio.rest.api.v2010.account.address.AddressContext - :rtype: twilio.rest.api.v2010.account.address.AddressContext + @property + def dependent_phone_numbers(self) -> DependentPhoneNumberList: + """ + Access the dependent_phone_numbers """ - return AddressContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.dependent_phone_numbers - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class AddressPage(Page): - """ """ +class AddressContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the AddressPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The SID of the Account that is responsible for the resource + Initialize the AddressContext - :returns: twilio.rest.api.v2010.account.address.AddressPage - :rtype: twilio.rest.api.v2010.account.address.AddressPage + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that is responsible for the Address resource to update. + :param sid: The Twilio-provided string that uniquely identifies the Address resource to update. """ - super(AddressPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Addresses/{sid}.json".format( + **self._solution + ) - def get_instance(self, payload): - """ - Build an instance of AddressInstance + self._dependent_phone_numbers: Optional[DependentPhoneNumberList] = None - :param dict payload: Payload response from the API + def _delete(self) -> tuple: + """ + Internal helper for delete operation - :returns: twilio.rest.api.v2010.account.address.AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - return AddressInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - Provide a friendly representation + Deletes the AddressInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + success, _, _ = self._delete() + return success + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AddressInstance and return response metadata -class AddressContext(InstanceContext): - """ """ - def __init__(self, version, account_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the AddressContext + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, 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 + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation - :returns: twilio.rest.api.v2010.account.address.AddressContext - :rtype: twilio.rest.api.v2010.account.address.AddressContext + Returns: + tuple: (success_boolean, status_code, headers) """ - super(AddressContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Addresses/{sid}.json'.format(**self._solution) + headers = values.of({}) - # Dependents - self._dependent_phone_numbers = None + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - def delete(self): + async def delete_async(self) -> bool: """ - Deletes the AddressInstance + Asynchronous coroutine that deletes the AddressInstance + :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + success, _, _ = await self._delete_async() + return success - def fetch(self): + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddressInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AddressInstance: """ Fetch the AddressInstance + :returns: The fetched AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AddressInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AddressInstance: + """ + Asynchronous coroutine to fetch the AddressInstance + + + :returns: The fetched AddressInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AddressInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: """ Update the AddressInstance - :param unicode friendly_name: 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 + :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._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, + ) + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the AddressInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) 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"], ) + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AddressInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + instance = AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @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 - @property - def account_sid(self): - """ - :returns: The SID of the Account that is responsible for the resource - :rtype: unicode - """ - return self._properties['account_sid'] + return AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def city(self): - """ - :returns: The city in which the address is located - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['city'] + Provide a friendly representation - @property - def customer_name(self): - """ - :returns: The name associated with the address - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['customer_name'] + 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 AddressList(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 AddressList - @property - def iso_country(self): - """ - :returns: The ISO country code of the address - :rtype: unicode - """ - return self._properties['iso_country'] + :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 postal_code(self): - """ - :returns: The postal code of the address - :rtype: unicode """ - return self._properties['postal_code'] + super().__init__(version) - @property - def region(self): + # 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - :returns: The state or region of the address - :rtype: unicode + 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 for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :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 """ - return self._properties['region'] + payload, _, _ = self._create( + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + iso_country=iso_country, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + return AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def sid(self): + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the AddressInstance and return response metadata + + :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 for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + iso_country=iso_country, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + instance = AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :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 unique string that identifies the resource - :rtype: unicode + payload, _, _ = await self._create_async( + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + iso_country=iso_country, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + return AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the AddressInstance and return response metadata + + :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 for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + iso_country=iso_country, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + instance = AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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['sid'] + 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 street(self): + :param str customer_name: The `customer_name` of the Address resources to read. + :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param str iso_country: The ISO country code of the Address resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The number and street address of the address - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = self.page( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AddressInstance]: """ - return self._properties['street'] + 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 uri(self): + :param str customer_name: The `customer_name` of the Address resources to read. + :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param str iso_country: The ISO country code of the Address resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + 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 stream_with_http_info( + 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, + ) -> tuple: """ - return self._properties['uri'] + Streams AddressInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: Whether emergency calling has been enabled on this number - :rtype: bool + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - return self._properties['emergency_enabled'] + Asynchronously streams AddressInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: Whether the address has been validated to comply with local regulation - :rtype: bool + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists AddressInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists AddressInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def delete(self): + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AddressPage(self._version, response, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with AddressPage, status code, and headers + """ + data = values.of( + { + "CustomerName": customer_name, + "FriendlyName": friendly_name, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "IsoCountry": iso_country, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AddressPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with AddressPage, status code, and headers + """ + data = values.of( + { + "CustomerName": customer_name, + "FriendlyName": friendly_name, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "IsoCountry": iso_country, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AddressPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of AddressInstance """ - Fetch the AddressInstance + response = self._version.domain.twilio.request("GET", target_url) + return AddressPage(self._version, response, solution=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, solution=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 a607099f9f..9a21e34d7c 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,560 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class DependentPhoneNumberInstance(InstanceResource): + + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" + + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" + + """ + :ivar sid: The unique string that that we created to identify the DependentPhoneNumber resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the DependentPhoneNumber resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar voice_url: The URL we call when the phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database. Can be: `true` or `false`. Caller ID lookups can cost $0.01 each. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call when the phone number receives an incoming SMS message. + :ivar address_requirements: + :ivar capabilities: The set of Boolean properties that indicates whether a phone number can receive calls or messages. Capabilities are `Voice`, `SMS`, and `MMS` and each capability can be: `true` or `false`. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar api_version: The API version used to start a new TwiML session. + :ivar sms_application_sid: The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :ivar voice_application_sid: The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :ivar trunk_sid: The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :ivar emergency_status: + :ivar emergency_address_sid: The SID of the emergency address configuration that we use for emergency calling from the phone number. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + address_sid: str, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.voice_url: Optional[str] = payload.get("voice_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" + ) + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.address_requirements: Optional[ + "DependentPhoneNumberInstance.AddressRequirement" + ] = payload.get("address_requirements") + self.capabilities: Optional[Dict[str, object]] = payload.get("capabilities") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.api_version: Optional[str] = payload.get("api_version") + self.sms_application_sid: Optional[str] = payload.get("sms_application_sid") + self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.emergency_status: Optional[ + "DependentPhoneNumberInstance.EmergencyStatus" + ] = payload.get("emergency_status") + self.emergency_address_sid: Optional[str] = payload.get("emergency_address_sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "address_sid": address_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DependentPhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DependentPhoneNumberInstance: + """ + Build an instance of DependentPhoneNumberInstance + + :param payload: Payload response from the API + """ + + return DependentPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + address_sid=self._solution["address_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class DependentPhoneNumberList(ListResource): - """ """ - def __init__(self, version, account_sid, address_sid): + def __init__(self, version: Version, account_sid: str, address_sid: str): """ 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 + :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. - :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) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, 'address_sid': address_sid, } - self._uri = '/Accounts/{account_sid}/Addresses/{address_sid}/DependentPhoneNumbers.json'.format(**self._solution) + 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): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DependentPhoneNumberInstance]: """ Streams DependentPhoneNumberInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberInstance] """ 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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DependentPhoneNumberInstance]: """ - Lists DependentPhoneNumberInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronously streams DependentPhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberInstance] """ - 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"]) - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Retrieve a single page of DependentPhoneNumberInstance records from the API. - Request is executed immediately + Streams DependentPhoneNumberInstance and returns headers from first page - :param str page_token: PageToken provided by the API - :param int page_number: 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, }) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - return DependentPhoneNumberPage(self._version, response, self._solution) + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - def get_page(self, target_url): + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Retrieve a specific page of DependentPhoneNumberInstance records from the API. - Request is executed immediately + Asynchronously streams DependentPhoneNumberInstance and returns headers from first page - :param str target_url: API-generated URL for the requested results page - :returns: Page of DependentPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberPage + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] ) - return DependentPhoneNumberPage(self._version, response, self._solution) + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - def __repr__(self): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentPhoneNumberInstance]: """ - Provide a friendly representation + Lists DependentPhoneNumberInstance 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 - """ - return '' + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + :returns: list that will contain up to limit results + """ -class DependentPhoneNumberPage(Page): - """ """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - def __init__(self, version, response, solution): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentPhoneNumberInstance]: """ - Initialize the DependentPhoneNumberPage + Asynchronously lists DependentPhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :param 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 + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberPage - :rtype: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberPage + :returns: list that will contain up to limit results """ - super(DependentPhoneNumberPage, self).__init__(version, response) - # Path Solution - self._solution = solution + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - def get_instance(self, payload): + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Build an instance of DependentPhoneNumberInstance + Lists DependentPhoneNumberInstance and returns headers from first page + - :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.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberInstance + :returns: ApiResponse with list of instances, status code, and headers """ - return DependentPhoneNumberInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - address_sid=self._solution['address_sid'], + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - def __repr__(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Provide a friendly representation + Asynchronously lists DependentPhoneNumberInstance and returns headers from first page - :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: ApiResponse with list of instances, status code, and headers """ - return '' + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DependentPhoneNumberPage: + """ + Retrieve a single page of DependentPhoneNumberInstance records from the API. + Request is executed immediately -class DependentPhoneNumberInstance(InstanceResource): - """ """ + :param page_token: PageToken provided by the 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 AddressRequirement(object): - NONE = "none" - ANY = "any" - LOCAL = "local" - FOREIGN = "foreign" + :returns: Page of DependentPhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - class EmergencyStatus(object): - ACTIVE = "Active" - INACTIVE = "Inactive" + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def __init__(self, version, payload, account_sid, address_sid): - """ - Initialize the DependentPhoneNumberInstance - - :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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'address_sid': address_sid, } + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentPhoneNumberPage( + self._version, response, solution=self._solution + ) - @property - def 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, + ) -> DependentPhoneNumberPage: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Asynchronously retrieve a single page of DependentPhoneNumberInstance 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 resource - :rtype: unicode + :returns: Page of DependentPhoneNumberInstance """ - return self._properties['friendly_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def phone_number(self): - """ - :returns: The phone number in E.164 format - :rtype: unicode - """ - return self._properties['phone_number'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def voice_url(self): - """ - :returns: The URL we call when the phone number receives a call - :rtype: unicode - """ - return self._properties['voice_url'] + headers["Accept"] = "application/json" - @property - def voice_method(self): - """ - :returns: The HTTP method used with the voice_url - :rtype: unicode - """ - return self._properties['voice_method'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentPhoneNumberPage( + self._version, response, solution=self._solution + ) - @property - def voice_fallback_method(self): - """ - :returns: The HTTP method used with voice_fallback_url - :rtype: unicode + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['voice_fallback_method'] + Retrieve a single page with response metadata - @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'] - @property - def voice_caller_id_lookup(self): - """ - :returns: Whether to lookup the caller's name - :rtype: bool - """ - return self._properties['voice_caller_id_lookup'] + :param page_token: PageToken provided by the 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: ApiResponse with DependentPhoneNumberPage, status code, and headers """ - return self._properties['date_created'] + data = values.of( + { + "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 sms_fallback_method(self): - """ - :returns: The HTTP method used with sms_fallback_url - :rtype: unicode - """ - return self._properties['sms_fallback_method'] + headers["Accept"] = "application/json" - @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'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DependentPhoneNumberPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def sms_method(self): - """ - :returns: The HTTP method to use with sms_url - :rtype: unicode + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['sms_method'] + Asynchronously retrieve a single page with response metadata - @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'] - @property - def address_requirements(self): - """ - :returns: Whether the phone number requires an Address registered with Twilio - :rtype: DependentPhoneNumberInstance.AddressRequirement - """ - return self._properties['address_requirements'] + :param page_token: PageToken provided by the 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 capabilities(self): - """ - :returns: Indicate if a phone can receive calls or messages - :rtype: dict + :returns: ApiResponse with DependentPhoneNumberPage, status code, and headers """ - return self._properties['capabilities'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def status_callback(self): - """ - :returns: The URL to send status information to your application - :rtype: unicode - """ - return self._properties['status_callback'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def status_callback_method(self): - """ - :returns: The HTTP method we use to call status_callback - :rtype: unicode - """ - return self._properties['status_callback_method'] + headers["Accept"] = "application/json" - @property - def api_version(self): - """ - :returns: The API version used to start a new TwiML session - :rtype: unicode - """ - return self._properties['api_version'] + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DependentPhoneNumberPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def sms_application_sid(self): + def get_page(self, target_url: str) -> DependentPhoneNumberPage: """ - :returns: The SID of the application that handles SMS messages sent to the phone number - :rtype: unicode - """ - return self._properties['sms_application_sid'] + Retrieve a specific page of DependentPhoneNumberInstance records from the API. + Request is executed immediately - @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 target_url: API-generated URL for the requested results page - @property - def trunk_sid(self): - """ - :returns: The SID of the Trunk that handles calls to the phone number - :rtype: unicode + :returns: Page of DependentPhoneNumberInstance """ - return self._properties['trunk_sid'] + response = self._version.domain.twilio.request("GET", target_url) + return DependentPhoneNumberPage( + self._version, response, solution=self._solution + ) - @property - def emergency_status(self): + async def get_page_async(self, target_url: str) -> DependentPhoneNumberPage: """ - :returns: Whether the phone number is enabled for emergency calling - :rtype: DependentPhoneNumberInstance.EmergencyStatus - """ - return self._properties['emergency_status'] + Asynchronously retrieve a specific page of DependentPhoneNumberInstance records from the API. + Request is executed immediately - @property - def emergency_address_sid(self): - """ - :returns: The emergency address configuration to use for emergency calling - :rtype: unicode - """ - return self._properties['emergency_address_sid'] + :param target_url: API-generated URL for the requested results page - @property - def uri(self): - """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + :returns: Page of DependentPhoneNumberInstance """ - return self._properties['uri'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return DependentPhoneNumberPage( + self._version, response, solution=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 e19bf9ee27..ba5a7926de 100644 --- a/twilio/rest/api/v2010/account/application.py +++ b/twilio/rest/api/v2010/account/application.py @@ -1,626 +1,985 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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, + } - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource + self._context: Optional[ApplicationContext] = None - :returns: twilio.rest.api.v2010.account.application.ApplicationList - :rtype: twilio.rest.api.v2010.account.application.ApplicationList + @property + def _proxy(self) -> "ApplicationContext": """ - super(ApplicationList, 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}/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): + :returns: ApplicationContext for this ApplicationInstance """ - Create 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 + if self._context is None: + self._context = ApplicationContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :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): + def delete(self) -> bool: """ - 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. + Deletes 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. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.application.ApplicationInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(friendly_name=friendly_name, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + return self._proxy.delete() - def list(self, friendly_name=values.unset, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists ApplicationInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes 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: 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 delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of ApplicationInstance records from the API. - Request is executed immediately + Deletes the ApplicationInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - data = values.of({ - 'FriendlyName': friendly_name, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.delete_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return ApplicationPage(self._version, response, self._solution) - - def get_page(self, target_url): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Retrieve a specific page of ApplicationInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the ApplicationInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.ApplicationPage + :returns: ApiResponse with success boolean, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.delete_with_http_info_async() - return ApplicationPage(self._version, response, self._solution) - - def get(self, sid): + def fetch(self) -> "ApplicationInstance": """ - Constructs a ApplicationContext + Fetch the ApplicationInstance - :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 """ - return ApplicationContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.fetch() - def __call__(self, sid): + async def fetch_async(self) -> "ApplicationInstance": """ - Constructs a ApplicationContext + Asynchronous coroutine to fetch the ApplicationInstance - :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 """ - return ApplicationContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.fetch_async() - def __repr__(self): + def fetch_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Fetch the ApplicationInstance with HTTP info - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - return '' + return self._proxy.fetch_with_http_info() + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApplicationInstance with HTTP info -class ApplicationPage(Page): - """ """ - def __init__(self, version, response, solution): + :returns: ApiResponse with instance, status code, and headers """ - Initialize the ApplicationPage + return await self._proxy.fetch_with_http_info_async() - :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 + 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": """ - super(ApplicationPage, self).__init__(version, response) + Update the ApplicationInstance - # Path Solution - self._solution = 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_instance(self, payload): + :returns: The updated ApplicationInstance """ - Build an instance of ApplicationInstance + return self._proxy.update( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) - :param dict payload: Payload response from the API + 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: twilio.rest.api.v2010.account.application.ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.ApplicationInstance + :returns: The updated ApplicationInstance """ - return ApplicationInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + return await self._proxy.update_async( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ApplicationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ApplicationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class ApplicationContext(InstanceContext): - """ """ - def __init__(self, version, account_sid, sid): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the ApplicationContext - :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 + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Application resources to update. + :param sid: The Twilio-provided string that uniquely identifies the Application resource to update. """ - super(ApplicationContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Applications/{sid}.json'.format(**self._solution) - - def delete(self): - """ - Deletes the ApplicationInstance + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Applications/{sid}.json".format( + **self._solution + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def _delete(self) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for delete operation - def fetch(self): + Returns: + tuple: (success_boolean, status_code, headers) """ - Fetch the ApplicationInstance - :returns: The fetched ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.ApplicationInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + headers = values.of({}) - return ApplicationInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers ) - def update(self, friendly_name=values.unset, api_version=values.unset, - voice_url=values.unset, voice_method=values.unset, - voice_fallback_url=values.unset, voice_fallback_method=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - voice_caller_id_lookup=values.unset, sms_url=values.unset, - sms_method=values.unset, sms_fallback_url=values.unset, - sms_fallback_method=values.unset, sms_status_callback=values.unset, - message_status_callback=values.unset): + def delete(self) -> bool: """ - Update the ApplicationInstance + Deletes 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 - :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, ) + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success - return ApplicationInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ApplicationInstance and return response metadata - def __repr__(self): + + :returns: ApiResponse with success boolean, status code, and headers """ - Provide a friendly representation + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :returns: Machine friendly representation - :rtype: str + async def _delete_async(self) -> tuple: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Internal async helper for delete operation + Returns: + tuple: (success_boolean, status_code, headers) + """ -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'), - } + headers = values.of({}) - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - @property - def _proxy(self): + async def delete_async(self) -> bool: """ - 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 that deletes the ApplicationInstance - :returns: ApplicationContext for this ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.ApplicationContext - """ - if self._context is None: - self._context = ApplicationContext( - self._version, - account_sid=self._solution['account_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 + :returns: True if delete succeeds, False otherwise """ - return self._properties['account_sid'] + success, _, _ = await self._delete_async() + return success - @property - def api_version(self): + async def delete_with_http_info_async(self) -> ApiResponse: """ - :returns: The API version used to start a new TwiML session - :rtype: unicode - """ - return self._properties['api_version'] + Asynchronous coroutine that deletes the ApplicationInstance and return response metadata - @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 + :returns: ApiResponse with success boolean, status code, and headers """ - return self._properties['date_updated'] + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + def _fetch(self) -> tuple: """ - return self._properties['friendly_name'] + Internal helper for fetch operation - @property - def message_status_callback(self): - """ - :returns: The URL to send message status information to your application - :rtype: unicode + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['message_status_callback'] - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + headers = values.of({}) - @property - def sms_fallback_method(self): - """ - :returns: The HTTP method used with sms_fallback_url - :rtype: unicode - """ - return self._properties['sms_fallback_method'] + headers["Accept"] = "application/json" - @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'] + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - @property - def sms_method(self): - """ - :returns: The HTTP method to use with sms_url - :rtype: unicode + def fetch(self) -> ApplicationInstance: """ - return self._properties['sms_method'] + Fetch the ApplicationInstance - @property - def sms_status_callback(self): - """ - :returns: The URL to send status information to your application - :rtype: unicode - """ - return self._properties['sms_status_callback'] - @property - def sms_url(self): - """ - :returns: The URL we call when the phone number receives an incoming SMS message - :rtype: unicode + :returns: The fetched ApplicationInstance """ - return self._properties['sms_url'] + payload, _, _ = self._fetch() + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - @property - def status_callback(self): + def fetch_with_http_info(self) -> ApiResponse: """ - :returns: The URL to send status information to your application - :rtype: unicode - """ - return self._properties['status_callback'] + Fetch the ApplicationInstance and return response metadata - @property - def status_callback_method(self): - """ - :returns: The HTTP method we use to call status_callback - :rtype: unicode - """ - return self._properties['status_callback_method'] - @property - def uri(self): - """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['uri'] + payload, status_code, headers = self._fetch() + instance = ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def voice_caller_id_lookup(self): + async def _fetch_async(self) -> tuple: """ - :returns: Whether to lookup the caller's name - :rtype: bool - """ - return self._properties['voice_caller_id_lookup'] + Internal async helper for fetch operation - @property - def voice_fallback_method(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The HTTP method used with voice_fallback_url - :rtype: unicode - """ - return self._properties['voice_fallback_method'] - @property - def voice_fallback_url(self): - """ - :returns: The URL we call when a TwiML error occurs - :rtype: unicode - """ - return self._properties['voice_fallback_url'] + headers = values.of({}) - @property - def voice_method(self): - """ - :returns: The HTTP method used with the voice_url - :rtype: unicode - """ - return self._properties['voice_method'] + headers["Accept"] = "application/json" - @property - def voice_url(self): - """ - :returns: The URL we call when the phone number receives a call - :rtype: unicode - """ - return self._properties['voice_url'] + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def delete(self): + async def fetch_async(self) -> ApplicationInstance: """ - Deletes the ApplicationInstance + Asynchronous coroutine to fetch the ApplicationInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched ApplicationInstance """ - return self._proxy.delete() + payload, _, _ = await self._fetch_async() + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Fetch the ApplicationInstance + Asynchronous coroutine to fetch the ApplicationInstance and return response metadata - :returns: The fetched ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.ApplicationInstance + + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.fetch() + payload, status_code, headers = await self._fetch_async() + instance = ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - def update(self, friendly_name=values.unset, api_version=values.unset, - voice_url=values.unset, voice_method=values.unset, - voice_fallback_url=values.unset, voice_fallback_method=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - voice_caller_id_lookup=values.unset, sms_url=values.unset, - sms_method=values.unset, sms_fallback_url=values.unset, - sms_fallback_method=values.unset, sms_status_callback=values.unset, - message_status_callback=values.unset): + def update( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApplicationInstance: """ Update the ApplicationInstance - :param unicode friendly_name: 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 + :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 - :rtype: twilio.rest.api.v2010.account.application.ApplicationInstance """ - return self._proxy.update( + payload, _, _ = self._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, + ) + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ApplicationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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 ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ApplicationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( friendly_name=friendly_name, api_version=api_version, voice_url=voice_url, @@ -636,14 +995,865 @@ def update(self, friendly_name=values.unset, api_version=values.unset, 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, + ) + instance = ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 ApplicationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ApplicationInstance: + """ + Build an instance of ApplicationInstance + + :param payload: Payload response from the API + """ + + return ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ApplicationList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the ApplicationList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Application resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Applications.json".format(**self._solution) + + def _create( + self, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApplicationInstance: + """ + Create the ApplicationInstance + + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is the account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param friendly_name: A descriptive string that you create to describe the new application. It can be up to 64 characters long. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The created ApplicationInstance + """ + payload, _, _ = self._create( + 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, + friendly_name=friendly_name, + public_application_connect_enabled=public_application_connect_enabled, + ) + return ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ApplicationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + 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, + friendly_name=friendly_name, + public_application_connect_enabled=public_application_connect_enabled, + ) + instance = ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + 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, + friendly_name=friendly_name, + public_application_connect_enabled=public_application_connect_enabled, + ) + return ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ApplicationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + 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, + friendly_name=friendly_name, + public_application_connect_enabled=public_application_connect_enabled, + ) + instance = ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ApplicationInstance]: + """ + Streams ApplicationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ApplicationInstance]: + """ + Asynchronously streams ApplicationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ApplicationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ApplicationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ApplicationInstance]: + """ + Lists ApplicationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ApplicationInstance]: + """ + Asynchronously lists ApplicationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ApplicationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ApplicationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApplicationPage: + """ + Retrieve a single page of ApplicationInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the Application resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ApplicationInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ApplicationPage(self._version, response, solution=self._solution) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApplicationPage: + """ + Asynchronously retrieve a single page of ApplicationInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the Application resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ApplicationInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ApplicationPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ApplicationPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ApplicationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ApplicationPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ApplicationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ApplicationPage: + """ + Retrieve a specific page of ApplicationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ApplicationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ApplicationPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ApplicationPage: + """ + Asynchronously retrieve a specific page of ApplicationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ApplicationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ApplicationPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> ApplicationContext: + """ + Constructs a ApplicationContext + + :param sid: The Twilio-provided string that uniquely identifies the Application resource to update. + """ + return ApplicationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ApplicationContext: + """ + Constructs a ApplicationContext + + :param sid: The Twilio-provided string that uniquely identifies the Application resource to update. + """ + return ApplicationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 56a0d75417..b608e9f141 100644 --- a/twilio/rest/api/v2010/account/authorized_connect_app.py +++ b/twilio/rest/api/v2010/account/authorized_connect_app.py @@ -1,395 +1,713 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class AuthorizedConnectAppList(ListResource): - """ """ +class AuthorizedConnectAppInstance(InstanceResource): - def __init__(self, version, account_sid): - """ - Initialize the AuthorizedConnectAppList + class Permission(object): + GET_ALL = "get-all" + POST_ALL = "post-all" - :param Version version: Version that contains the resource - :param account_sid: The 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 AuthorizedConnectApp resource. + :ivar connect_app_company_name: The company name set for the Connect App. + :ivar connect_app_description: A detailed description of the Connect App. + :ivar connect_app_friendly_name: The name of the Connect App. + :ivar connect_app_homepage_url: The public URL for the Connect App. + :ivar connect_app_sid: The SID that we assigned to the Connect App. + :ivar permissions: The set of permissions that you authorized for the Connect App. Can be: `get-all` or `post-all`. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + connect_app_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.connect_app_company_name: Optional[str] = payload.get( + "connect_app_company_name" + ) + self.connect_app_description: Optional[str] = payload.get( + "connect_app_description" + ) + self.connect_app_friendly_name: Optional[str] = payload.get( + "connect_app_friendly_name" + ) + self.connect_app_homepage_url: Optional[str] = payload.get( + "connect_app_homepage_url" + ) + self.connect_app_sid: Optional[str] = payload.get("connect_app_sid") + self.permissions: Optional[List["AuthorizedConnectAppInstance.Permission"]] = ( + payload.get("permissions") + ) + self.uri: Optional[str] = payload.get("uri") - :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList - """ - super(AuthorizedConnectAppList, self).__init__(version) + self._solution = { + "account_sid": account_sid, + "connect_app_sid": connect_app_sid or self.connect_app_sid, + } - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/AuthorizedConnectApps.json'.format(**self._solution) + self._context: Optional[AuthorizedConnectAppContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "AuthorizedConnectAppContext": """ - 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. + 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: 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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppInstance] + def fetch(self) -> "AuthorizedConnectAppInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the AuthorizedConnectAppInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched AuthorizedConnectAppInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the AuthorizedConnectAppInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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 """ - 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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of AuthorizedConnectAppInstance records from the API. - Request is executed immediately + Fetch the AuthorizedConnectAppInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthorizedConnectAppInstance with HTTP info - return AuthorizedConnectAppPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of AuthorizedConnectAppInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_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) - :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 +class AuthorizedConnectAppContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, connect_app_sid: str): """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Initialize the AuthorizedConnectAppContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AuthorizedConnectApp resource to fetch. + :param connect_app_sid: The SID of the Connect App to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "connect_app_sid": connect_app_sid, + } + self._uri = "/Accounts/{account_sid}/AuthorizedConnectApps/{connect_app_sid}.json".format( + **self._solution ) - return AuthorizedConnectAppPage(self._version, response, self._solution) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) - def get(self, connect_app_sid): + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthorizedConnectAppInstance: """ - Constructs a AuthorizedConnectAppContext + 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( + payload, _, _ = self._fetch() + 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a AuthorizedConnectAppContext + Fetch the AuthorizedConnectAppInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return AuthorizedConnectAppContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class AuthorizedConnectAppPage(Page): - """ """ + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + async def fetch_async(self) -> AuthorizedConnectAppInstance: """ - Initialize the AuthorizedConnectAppPage + Asynchronous coroutine to fetch the AuthorizedConnectAppInstance - :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 + :returns: The fetched AuthorizedConnectAppInstance """ - super(AuthorizedConnectAppPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = await self._fetch_async() + return AuthorizedConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + connect_app_sid=self._solution["connect_app_sid"], + ) - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of AuthorizedConnectAppInstance + Asynchronous coroutine to fetch the AuthorizedConnectAppInstance and return response metadata - :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 + :returns: ApiResponse with instance, status code, and headers """ - return AuthorizedConnectAppInstance( + payload, status_code, headers = await self._fetch_async() + instance = AuthorizedConnectAppInstance( self._version, payload, - account_sid=self._solution['account_sid'], + account_sid=self._solution["account_sid"], + connect_app_sid=self._solution["connect_app_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 AuthorizedConnectAppContext(InstanceContext): - """ """ +class AuthorizedConnectAppPage(Page): - def __init__(self, version, account_sid, connect_app_sid): + def get_instance(self, payload: Dict[str, Any]) -> AuthorizedConnectAppInstance: + """ + Build an instance of AuthorizedConnectAppInstance + + :param payload: Payload response from the API """ - Initialize the AuthorizedConnectAppContext - :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 + return AuthorizedConnectAppInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppContext - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppContext + def __repr__(self) -> str: """ - super(AuthorizedConnectAppContext, self).__init__(version) + Provide a friendly representation - # 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) + :returns: Machine friendly representation + """ + return "" + + +class AuthorizedConnectAppList(ListResource): - def fetch(self): + def __init__(self, version: Version, account_sid: str): """ - Fetch the AuthorizedConnectAppInstance + Initialize the AuthorizedConnectAppList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AuthorizedConnectApp resources to read. - :returns: The fetched AuthorizedConnectAppInstance - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + super().__init__(version) - return AuthorizedConnectAppInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - connect_app_sid=self._solution['connect_app_sid'], + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/AuthorizedConnectApps.json".format( + **self._solution ) - def __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AuthorizedConnectAppInstance]: """ - Provide a friendly representation + 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 = self.page(page_size=limits["page_size"]) + return self._version.stream(page, limits["limit"]) -class AuthorizedConnectAppInstance(InstanceResource): - """ """ + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AuthorizedConnectAppInstance]: + """ + Asynchronously streams AuthorizedConnectAppInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - class Permission(object): - GET_ALL = "get-all" - POST_ALL = "post-all" + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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, connect_app_sid=None): + :returns: Generator that will yield up to limit results """ - Initialize the AuthorizedConnectAppInstance + limits = self._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.authorized_connect_app.AuthorizedConnectAppInstance - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppInstance + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(AuthorizedConnectAppInstance, self).__init__(version) + Streams AuthorizedConnectAppInstance and returns headers from first page - # 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'], - } + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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: tuple of (generator, status_code, headers) where generator yields instances """ - 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_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: AuthorizedConnectAppContext for this AuthorizedConnectAppInstance - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppContext + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - if self._context is None: - self._context = AuthorizedConnectAppContext( - self._version, - account_sid=self._solution['account_sid'], - connect_app_sid=self._solution['connect_app_sid'], + Asynchronously streams AuthorizedConnectAppInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizedConnectAppInstance]: + """ + Lists AuthorizedConnectAppInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def account_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizedConnectAppInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Asynchronously lists AuthorizedConnectAppInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['account_sid'] - @property - def connect_app_company_name(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The company name set for the Connect App - :rtype: unicode + Lists AuthorizedConnectAppInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['connect_app_company_name'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def connect_app_description(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: A detailed description of the app - :rtype: unicode + Asynchronously lists AuthorizedConnectAppInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['connect_app_description'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def connect_app_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, + ) -> AuthorizedConnectAppPage: """ - :returns: The name of the Connect App - :rtype: unicode + 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['connect_app_friendly_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def connect_app_homepage_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 AuthorizedConnectAppPage( + self._version, response, solution=self._solution + ) + + async def 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 public URL for the Connect App - :rtype: unicode + 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['connect_app_homepage_url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def connect_app_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 AuthorizedConnectAppPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The SID that we assigned to the Connect App - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthorizedConnectAppPage, status code, and headers """ - return self._properties['connect_app_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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AuthorizedConnectAppPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthorizedConnectAppPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AuthorizedConnectAppPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 b38d729e16..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists AvailablePhoneNumberCountryInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of AvailablePhoneNumberCountryInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of AvailablePhoneNumberCountryInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryPage - """ - 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 8eb14f3603..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'], limits['page_limit']) - - def list(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - Lists LocalInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode area_code: The area code 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 4a8d11af6d..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'], limits['page_limit']) - - def list(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - Lists MachineToMachineInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode area_code: The area code 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 2e57c6ff6c..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'], limits['page_limit']) - - def list(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - Lists MobileInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode area_code: The area code 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 8df9c6dbd4..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'], limits['page_limit']) - - def list(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - Lists NationalInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode area_code: The area code 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 6234d34327..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'], limits['page_limit']) - - def list(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - Lists SharedCostInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode area_code: The area code 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 2acad4e20e..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'], limits['page_limit']) - - def list(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - Lists TollFreeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode area_code: The area code 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 91ec440423..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'], limits['page_limit']) - - def list(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - Lists VoipInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode area_code: The area code 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..4b8207514d --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/__init__.py @@ -0,0 +1,867 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailablePhoneNumberCountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailablePhoneNumberCountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AvailablePhoneNumberCountryInstance: + """ + Fetch the AvailablePhoneNumberCountryInstance + + + :returns: The fetched AvailablePhoneNumberCountryInstance + """ + payload, _, _ = self._fetch() + return AvailablePhoneNumberCountryInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailablePhoneNumberCountryInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AvailablePhoneNumberCountryInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AvailablePhoneNumberCountryInstance: + """ + Asynchronous coroutine to fetch the AvailablePhoneNumberCountryInstance + + + :returns: The fetched AvailablePhoneNumberCountryInstance + """ + payload, _, _ = await self._fetch_async() + return AvailablePhoneNumberCountryInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailablePhoneNumberCountryInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AvailablePhoneNumberCountryInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AvailablePhoneNumberCountryInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AvailablePhoneNumberCountryInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AvailablePhoneNumberCountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AvailablePhoneNumberCountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution + ) + + async def 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, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailablePhoneNumberCountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AvailablePhoneNumberCountryPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailablePhoneNumberCountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AvailablePhoneNumberCountryPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..dd014b8221 --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/local.py @@ -0,0 +1,1176 @@ +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.api_response import ApiResponse + +from twilio.base.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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams LocalInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams LocalInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists LocalInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists LocalInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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, solution=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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with LocalPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = LocalPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with LocalPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = LocalPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..8413389849 --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/machine_to_machine.py @@ -0,0 +1,1176 @@ +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.api_response import ApiResponse + +from twilio.base.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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams MachineToMachineInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams MachineToMachineInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists MachineToMachineInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists MachineToMachineInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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, solution=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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with MachineToMachinePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MachineToMachinePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with MachineToMachinePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MachineToMachinePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..393c3433a5 --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/mobile.py @@ -0,0 +1,1176 @@ +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.api_response import ApiResponse + +from twilio.base.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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams MobileInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams MobileInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists MobileInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists MobileInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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, solution=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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with MobilePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MobilePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with MobilePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MobilePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..1f1bf33a76 --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/national.py @@ -0,0 +1,1176 @@ +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.api_response import ApiResponse + +from twilio.base.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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams NationalInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams NationalInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists NationalInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists NationalInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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, solution=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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with NationalPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = NationalPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with NationalPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = NationalPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..fa9e3332c8 --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/shared_cost.py @@ -0,0 +1,1176 @@ +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.api_response import ApiResponse + +from twilio.base.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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams SharedCostInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams SharedCostInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists SharedCostInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists SharedCostInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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, solution=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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with SharedCostPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SharedCostPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with SharedCostPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SharedCostPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..de41071b08 --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/toll_free.py @@ -0,0 +1,1176 @@ +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.api_response import ApiResponse + +from twilio.base.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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams TollFreeInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams TollFreeInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists TollFreeInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists TollFreeInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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, solution=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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with TollFreePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TollFreePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with TollFreePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TollFreePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..0c319a53df --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/voip.py @@ -0,0 +1,1176 @@ +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.api_response import ApiResponse + +from twilio.base.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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams VoipInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams VoipInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists VoipInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists VoipInstance and returns headers from first page + + + :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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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, solution=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: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with VoipPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = VoipPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :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: ApiResponse with VoipPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = VoipPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..106e76e33d 100644 --- a/twilio/rest/api/v2010/account/balance.py +++ b/twilio/rest/api/v2010/account/balance.py @@ -1,149 +1,156 @@ -# 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.api_response import ApiResponse + 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) -> tuple: """ - Build an instance of BalanceInstance + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - :param dict payload: Payload response from the API + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - :returns: twilio.rest.api.v2010.account.balance.BalanceInstance - :rtype: twilio.rest.api.v2010.account.balance.BalanceInstance + def fetch(self) -> BalanceInstance: """ - return BalanceInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Fetch the BalanceInstance + - def __repr__(self): + :returns: The fetched BalanceInstance """ - Provide a friendly representation + payload, _, _ = self._fetch() + return BalanceInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - :returns: Machine friendly representation - :rtype: str + def fetch_with_http_info(self) -> ApiResponse: """ - return '' + Fetch the BalanceInstance and return response metadata -class BalanceInstance(InstanceResource): - """ """ + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BalanceInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __init__(self, version, payload, account_sid): + async def _fetch_async(self) -> tuple: """ - Initialize the BalanceInstance + Internal async helper for fetch operation - :returns: twilio.rest.api.v2010.account.balance.BalanceInstance - :rtype: twilio.rest.api.v2010.account.balance.BalanceInstance + Returns: + tuple: (payload, status_code, headers) """ - super(BalanceInstance, self).__init__(version) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'balance': payload.get('balance'), - 'currency': payload.get('currency'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - @property - def account_sid(self): + async def fetch_async(self) -> BalanceInstance: """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] + Asynchronously fetch the BalanceInstance - @property - def balance(self): - """ - :returns: Account balance - :rtype: unicode + + :returns: The fetched BalanceInstance """ - return self._properties['balance'] + payload, _, _ = await self._fetch_async() + return BalanceInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def currency(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: Currency units - :rtype: unicode + Asynchronously fetch the BalanceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['currency'] + payload, status_code, headers = await self._fetch_async() + instance = BalanceInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 a3f42c0373..23b0121ee4 100644 --- a/twilio/rest/api/v2010/account/call/__init__.py +++ b/twilio/rest/api/v2010/account/call/__init__.py @@ -1,952 +1,2549 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): - """ - Create the CallInstance + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } - :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 (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 + self._context: Optional[CallContext] = None - :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): + @property + def _proxy(self) -> "CallContext": """ - Streams CallInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param unicode to: Phone number or Client identifier 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: CallContext for this CallInstance + """ + if self._context is None: + self._context = CallContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.call.CallInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the CallInstance - page = self.page( - to=to, - from_=from_, - parent_call_sid=parent_call_sid, - status=status, - start_time_before=start_time_before, - start_time=start_time, - start_time_after=start_time_after, - end_time_before=end_time_before, - end_time=end_time, - end_time_after=end_time_after, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, to=values.unset, from_=values.unset, - parent_call_sid=values.unset, status=values.unset, - start_time_before=values.unset, start_time=values.unset, - start_time_after=values.unset, end_time_before=values.unset, - end_time=values.unset, end_time_after=values.unset, limit=None, - page_size=None): + async def delete_async(self) -> bool: """ - Lists CallInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the CallInstance - :param unicode to: Phone number or Client identifier 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) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.call.CallInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - to=to, - from_=from_, - parent_call_sid=parent_call_sid, - status=status, - start_time_before=start_time_before, - start_time=start_time, - start_time_after=start_time_after, - end_time_before=end_time_before, - end_time=end_time, - end_time_after=end_time_after, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_async() - 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): + def delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of CallInstance records from the API. - Request is executed immediately + Deletes the CallInstance with HTTP info - :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, ) - - return CallPage(self._version, response, self._solution) - - def get_page(self, target_url): + :returns: ApiResponse with success boolean, status code, and headers """ - Retrieve a specific page of CallInstance records from the API. - Request is executed immediately + return self._proxy.delete_with_http_info() - :param str target_url: API-generated URL for the requested results page + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CallInstance with HTTP info - :returns: Page of CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallPage + + :returns: ApiResponse with success boolean, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "CallInstance": + """ + Fetch the CallInstance - return CallPage(self._version, response, self._solution) - @property - def feedback_summaries(self): + :returns: The fetched CallInstance """ - Access the feedback_summaries + return self._proxy.fetch() - :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList - :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList + async def fetch_async(self) -> "CallInstance": """ - if self._feedback_summaries is None: - self._feedback_summaries = FeedbackSummaryList( - self._version, - account_sid=self._solution['account_sid'], - ) - return self._feedback_summaries + Asynchronous coroutine to fetch the CallInstance + + + :returns: The fetched CallInstance + """ + return await self._proxy.fetch_async() - def get(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a CallContext + Fetch the CallInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return CallContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.fetch_with_http_info() - def __call__(self, sid): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Constructs a CallContext + Asynchronous coroutine to fetch the CallInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return CallContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.fetch_with_http_info_async() - def __repr__(self): + 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": """ - Provide a friendly representation + Update the CallInstance - :returns: Machine friendly representation - :rtype: str + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: The updated CallInstance """ - return '' + return self._proxy.update( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + async def update_async( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> "CallInstance": + """ + Asynchronous coroutine to update the CallInstance + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. -class CallPage(Page): - """ """ + :returns: The updated CallInstance + """ + return await self._proxy.update_async( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CallInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CallInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) - def __init__(self, version, response, solution): + @property + def events(self) -> EventList: """ - Initialize the CallPage + Access the events + """ + return self._proxy.events - :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 + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + return self._proxy.notifications - :returns: twilio.rest.api.v2010.account.call.CallPage - :rtype: twilio.rest.api.v2010.account.call.CallPage + @property + def payments(self) -> PaymentList: + """ + Access the payments """ - super(CallPage, self).__init__(version, response) + return self._proxy.payments - # Path Solution - self._solution = solution + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + return self._proxy.recordings - def get_instance(self, payload): + @property + def siprec(self) -> SiprecList: """ - Build an instance of CallInstance + Access the siprec + """ + return self._proxy.siprec + + @property + def streams(self) -> StreamList: + """ + Access the streams + """ + return self._proxy.streams + + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + return self._proxy.transcriptions - :param dict payload: Payload response from the API + @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.CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallInstance + @property + def user_defined_message_subscriptions(self) -> UserDefinedMessageSubscriptionList: + """ + Access the user_defined_message_subscriptions """ - return CallInstance(self._version, payload, account_sid=self._solution['account_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 CallContext(InstanceContext): - """ """ - def __init__(self, version, account_sid, sid): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the CallContext - :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 + :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(CallContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Calls/{sid}.json'.format(**self._solution) + self._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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - # Dependents - self._recordings = None - self._notifications = None - self._feedback = None - self._payments = None + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - def delete(self): + def delete(self) -> bool: """ Deletes the CallInstance + :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + success, _, _ = self._delete() + return success - def fetch(self): + def delete_with_http_info(self) -> ApiResponse: """ - Fetch the CallInstance + Deletes the CallInstance and return response metadata - :returns: The fetched CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallInstance + + :returns: ApiResponse with success boolean, status code, and headers """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - return CallInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation - 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: + tuple: (success_boolean, status_code, headers) """ - 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 + headers = values.of({}) - :returns: The updated CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallInstance + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - data = values.of({ - 'Url': url, - 'Method': method, - 'Status': status, - 'FallbackUrl': fallback_url, - 'FallbackMethod': fallback_method, - 'StatusCallback': status_callback, - 'StatusCallbackMethod': status_callback_method, - 'Twiml': twiml, - }) + Asynchronous coroutine that deletes the CallInstance - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - return CallInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success - @property - def recordings(self): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Access the recordings + Asynchronous coroutine that deletes the CallInstance and return response metadata - :returns: twilio.rest.api.v2010.account.call.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingList + + :returns: ApiResponse with success boolean, status code, and headers """ - if self._recordings is None: - self._recordings = RecordingList( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['sid'], - ) - return self._recordings + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - @property - def notifications(self): + def _fetch(self) -> tuple: """ - Access the notifications + Internal helper for fetch operation - :returns: twilio.rest.api.v2010.account.call.notification.NotificationList - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationList + Returns: + tuple: (payload, status_code, headers) """ - if self._notifications is None: - self._notifications = NotificationList( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['sid'], - ) - return self._notifications - @property - def feedback(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CallInstance: """ - Access the feedback + Fetch the CallInstance + - :returns: twilio.rest.api.v2010.account.call.feedback.FeedbackList - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackList + :returns: The fetched CallInstance """ - if self._feedback is None: - self._feedback = FeedbackList( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['sid'], - ) - return self._feedback + payload, _, _ = self._fetch() + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - @property - def payments(self): + def fetch_with_http_info(self) -> ApiResponse: """ - Access the payments + Fetch the CallInstance and return response metadata + - :returns: twilio.rest.api.v2010.account.call.payment.PaymentList - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentList + :returns: ApiResponse with instance, status code, and headers """ - if self._payments is None: - self._payments = PaymentList( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['sid'], - ) - return self._payments + payload, status_code, headers = self._fetch() + instance = CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) -class CallInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - class Event(object): - INITIATED = "initiated" - RINGING = "ringing" - ANSWERED = "answered" - COMPLETED = "completed" + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - class Status(object): - QUEUED = "queued" - RINGING = "ringing" - IN_PROGRESS = "in-progress" - COMPLETED = "completed" - BUSY = "busy" - FAILED = "failed" - NO_ANSWER = "no-answer" - CANCELED = "canceled" - - class UpdateStatus(object): - CANCELED = "canceled" - COMPLETED = "completed" - - def __init__(self, version, payload, account_sid, sid=None): - """ - Initialize the CallInstance - - :returns: twilio.rest.api.v2010.account.call.CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallInstance - """ - super(CallInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'annotation': payload.get('annotation'), - 'answered_by': payload.get('answered_by'), - 'api_version': payload.get('api_version'), - 'caller_name': payload.get('caller_name'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'direction': payload.get('direction'), - 'duration': payload.get('duration'), - 'end_time': deserialize.rfc2822_datetime(payload.get('end_time')), - 'forwarded_from': payload.get('forwarded_from'), - 'from_': payload.get('from'), - 'from_formatted': payload.get('from_formatted'), - 'group_sid': payload.get('group_sid'), - 'parent_call_sid': payload.get('parent_call_sid'), - 'phone_number_sid': payload.get('phone_number_sid'), - 'price': payload.get('price'), - 'price_unit': payload.get('price_unit'), - 'sid': payload.get('sid'), - 'start_time': deserialize.rfc2822_datetime(payload.get('start_time')), - 'status': payload.get('status'), - 'subresource_uris': payload.get('subresource_uris'), - 'to': payload.get('to'), - 'to_formatted': payload.get('to_formatted'), - 'trunk_sid': payload.get('trunk_sid'), - 'uri': payload.get('uri'), - 'queue_time': payload.get('queue_time'), - } + async def fetch_async(self) -> CallInstance: + """ + Asynchronous coroutine to fetch the CallInstance - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): + :returns: The fetched CallInstance """ - 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._fetch_async() + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - :returns: CallContext for this CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallContext + async def fetch_with_http_info_async(self) -> ApiResponse: """ - if self._context is None: - self._context = CallContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + Asynchronous coroutine to fetch the CallInstance and return response metadata - @property - def account_sid(self): - """ - :returns: The SID of the Account that created this resource - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def annotation(self): - """ - :returns: The annotation provided for the call - :rtype: unicode + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['annotation'] + payload, status_code, headers = await self._fetch_async() + instance = CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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({}) - @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'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def api_version(self): - """ - :returns: The API Version used to create the call - :rtype: unicode - """ - return self._properties['api_version'] + headers["Accept"] = "application/json" - @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'] + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that this resource was created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Update the CallInstance - @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'] + :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. - @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 + :returns: The updated CallInstance """ - return self._properties['direction'] + payload, _, _ = self._update( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - @property - def duration(self): - """ - :returns: The length of the call in seconds. - :rtype: unicode - """ - return self._properties['duration'] + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CallInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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({}) - @property - def end_time(self): - """ - :returns: The end time of the call. Null if the call did not complete successfully. - :rtype: datetime - """ - return self._properties['end_time'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @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 + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> CallInstance: + """ + Asynchronous coroutine to update the CallInstance + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: The updated CallInstance """ - return self._properties['forwarded_from'] + payload, _, _ = await self._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 CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CallInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def from_(self): + def events(self) -> EventList: """ - :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 + Access the events """ - return self._properties['from_'] + if self._events is None: + self._events = EventList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._events @property - def from_formatted(self): + def notifications(self) -> NotificationList: """ - :returns: The calling phone number, SIP address, or Client identifier formatted for display. - :rtype: unicode + Access the notifications """ - return self._properties['from_formatted'] + if self._notifications is None: + self._notifications = NotificationList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._notifications @property - def group_sid(self): + def payments(self) -> PaymentList: """ - :returns: The Group SID associated with this call. If no Group is associated with the call, the field is empty. - :rtype: unicode + Access the payments """ - return self._properties['group_sid'] + if self._payments is None: + self._payments = PaymentList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._payments @property - def parent_call_sid(self): + def recordings(self) -> RecordingList: """ - :returns: The SID that identifies the call that created this leg. - :rtype: unicode + Access the recordings """ - return self._properties['parent_call_sid'] + if self._recordings is None: + self._recordings = RecordingList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._recordings @property - def phone_number_sid(self): + def siprec(self) -> SiprecList: """ - :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 + Access the siprec """ - return self._properties['phone_number_sid'] + if self._siprec is None: + self._siprec = SiprecList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._siprec @property - def price(self): + def streams(self) -> StreamList: """ - :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 + Access the streams """ - return self._properties['price'] + if self._streams is None: + self._streams = StreamList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._streams @property - def price_unit(self): + def transcriptions(self) -> TranscriptionList: """ - :returns: The currency in which `Price` is measured. - :rtype: unicode + Access the transcriptions """ - return self._properties['price_unit'] + if self._transcriptions is None: + self._transcriptions = TranscriptionList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._transcriptions @property - def sid(self): + def user_defined_messages(self) -> UserDefinedMessageList: """ - :returns: The unique string that identifies this resource - :rtype: unicode + Access the user_defined_messages """ - return self._properties['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 start_time(self): + def user_defined_message_subscriptions(self) -> UserDefinedMessageSubscriptionList: """ - :returns: The start time of the call. Null if the call has not yet been dialed. - :rtype: datetime + Access the user_defined_message_subscriptions """ - return self._properties['start_time'] + 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 status(self): + def __repr__(self) -> str: """ - :returns: The status of this call. - :rtype: CallInstance.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 subresource_uris(self): + +class CallPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CallInstance: """ - :returns: A list of related subresources identified by their relative URIs - :rtype: unicode + Build an instance of CallInstance + + :param payload: Payload response from the API """ - return self._properties['subresource_uris'] - @property - def to(self): + return CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: """ - :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 + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['to'] + return "" - @property - def to_formatted(self): + +class CallList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - :returns: The phone number, SIP address or Client identifier that received this call. Formatted for display. - :rtype: unicode + Initialize the CallList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call resource(s) to read. + """ - return self._properties['to_formatted'] + super().__init__(version) - @property - def trunk_sid(self): + # 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, + recording_configuration_id: 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, + client_notification_url: Union[str, object] = values.unset, + url: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "RecordingConfigurationId": recording_configuration_id, + "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, + "ClientNotificationUrl": client_notification_url, + "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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + recording_configuration_id: 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, + client_notification_url: Union[str, object] = values.unset, + url: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + ) -> CallInstance: """ - :returns: The (optional) unique identifier of the trunk resource that was used for this call. - :rtype: unicode + 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 recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :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 client_notification_url: The URL that we should use to deliver `push call notification`. + :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 """ - return self._properties['trunk_sid'] + payload, _, _ = self._create( + to=to, + from_=from_, + method=method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_event=status_callback_event, + status_callback_method=status_callback_method, + send_digits=send_digits, + timeout=timeout, + record=record, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_configuration_id=recording_configuration_id, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + machine_detection=machine_detection, + machine_detection_timeout=machine_detection_timeout, + recording_status_callback_event=recording_status_callback_event, + trim=trim, + caller_id=caller_id, + 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, + async_amd=async_amd, + async_amd_status_callback=async_amd_status_callback, + async_amd_status_callback_method=async_amd_status_callback_method, + byoc=byoc, + call_reason=call_reason, + call_token=call_token, + recording_track=recording_track, + time_limit=time_limit, + client_notification_url=client_notification_url, + url=url, + twiml=twiml, + application_sid=application_sid, + ) + return CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def uri(self): + def create_with_http_info( + 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, + recording_configuration_id: 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, + client_notification_url: Union[str, object] = values.unset, + url: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CallInstance and return response metadata + + :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 recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :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 client_notification_url: The URL that we should use to deliver `push call notification`. + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + to=to, + from_=from_, + method=method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_event=status_callback_event, + status_callback_method=status_callback_method, + send_digits=send_digits, + timeout=timeout, + record=record, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_configuration_id=recording_configuration_id, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + machine_detection=machine_detection, + machine_detection_timeout=machine_detection_timeout, + recording_status_callback_event=recording_status_callback_event, + trim=trim, + caller_id=caller_id, + 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, + async_amd=async_amd, + async_amd_status_callback=async_amd_status_callback, + async_amd_status_callback_method=async_amd_status_callback_method, + byoc=byoc, + call_reason=call_reason, + call_token=call_token, + recording_track=recording_track, + time_limit=time_limit, + client_notification_url=client_notification_url, + url=url, + twiml=twiml, + application_sid=application_sid, + ) + instance = CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + recording_configuration_id: 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, + client_notification_url: Union[str, object] = values.unset, + url: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "RecordingConfigurationId": recording_configuration_id, + "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, + "ClientNotificationUrl": client_notification_url, + "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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + recording_configuration_id: 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, + client_notification_url: Union[str, 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 recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :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 client_notification_url: The URL that we should use to deliver `push call notification`. + :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: The URI of this resource, relative to `https://api.twilio.com` - :rtype: unicode + payload, _, _ = await self._create_async( + to=to, + from_=from_, + method=method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_event=status_callback_event, + status_callback_method=status_callback_method, + send_digits=send_digits, + timeout=timeout, + record=record, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_configuration_id=recording_configuration_id, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + machine_detection=machine_detection, + machine_detection_timeout=machine_detection_timeout, + recording_status_callback_event=recording_status_callback_event, + trim=trim, + caller_id=caller_id, + 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, + async_amd=async_amd, + async_amd_status_callback=async_amd_status_callback, + async_amd_status_callback_method=async_amd_status_callback_method, + byoc=byoc, + call_reason=call_reason, + call_token=call_token, + recording_track=recording_track, + time_limit=time_limit, + client_notification_url=client_notification_url, + url=url, + twiml=twiml, + application_sid=application_sid, + ) + return CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_with_http_info_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, + recording_configuration_id: 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, + client_notification_url: Union[str, object] = values.unset, + url: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CallInstance and return response metadata + + :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 recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :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 client_notification_url: The URL that we should use to deliver `push call notification`. + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + to=to, + from_=from_, + method=method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_event=status_callback_event, + status_callback_method=status_callback_method, + send_digits=send_digits, + timeout=timeout, + record=record, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_configuration_id=recording_configuration_id, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + machine_detection=machine_detection, + machine_detection_timeout=machine_detection_timeout, + recording_status_callback_event=recording_status_callback_event, + trim=trim, + caller_id=caller_id, + 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, + async_amd=async_amd, + async_amd_status_callback=async_amd_status_callback, + async_amd_status_callback_method=async_amd_status_callback_method, + byoc=byoc, + call_reason=call_reason, + call_token=call_token, + recording_track=recording_track, + time_limit=time_limit, + client_notification_url=client_notification_url, + url=url, + twiml=twiml, + application_sid=application_sid, + ) + instance = CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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['uri'] + Streams CallInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - @property - def queue_time(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. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after 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. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after 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 wait time in milliseconds before the call is placed. - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = self.page( + to=to, + from_=from_, + parent_call_sid=parent_call_sid, + status=status, + start_time=start_time, + start_time_before=start_time_before, + start_time_after=start_time_after, + end_time=end_time, + end_time_before=end_time_before, + end_time_after=end_time_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CallInstance]: + """ + Asynchronously streams CallInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param str parent_call_sid: Only include calls spawned by calls with this SID. + :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after 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. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['queue_time'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + to=to, + from_=from_, + parent_call_sid=parent_call_sid, + status=status, + start_time=start_time, + start_time_before=start_time_before, + start_time_after=start_time_after, + end_time=end_time, + end_time_before=end_time_before, + end_time_after=end_time_after, + page_size=limits["page_size"], + ) - def delete(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams CallInstance and returns headers from first page + + + :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. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after 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. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after 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: tuple of (generator, status_code, headers) where generator yields instances """ - Deletes the CallInstance + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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 + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams CallInstance and returns headers from first page + + + :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. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after 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. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after 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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._proxy.delete() + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after 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. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after 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. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after 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. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists CallInstance and returns headers from first page + + + :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. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after 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. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists CallInstance and returns headers from first page + + + :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. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after 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. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 - 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): + :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. + :param start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after 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. + :param end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after 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 """ - 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, solution=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. + :param start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after 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. + :param end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after 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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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. + :param start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after 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. + :param end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after 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: ApiResponse with CallPage, status code, and headers + """ + data = values.of( + { + "To": to, + "From": from_, + "ParentCallSid": parent_call_sid, + "Status": status, + "StartTime": serialize.iso8601_datetime(start_time), + "StartTime<": serialize.iso8601_datetime(start_time_before), + "StartTime>": serialize.iso8601_datetime(start_time_after), + "EndTime": serialize.iso8601_datetime(end_time), + "EndTime<": serialize.iso8601_datetime(end_time_before), + "EndTime>": serialize.iso8601_datetime(end_time_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CallPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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. + :param start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after 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. + :param end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after 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: ApiResponse with CallPage, status code, and headers + """ + data = values.of( + { + "To": to, + "From": from_, + "ParentCallSid": parent_call_sid, + "Status": status, + "StartTime": serialize.iso8601_datetime(start_time), + "StartTime<": serialize.iso8601_datetime(start_time_before), + "StartTime>": serialize.iso8601_datetime(start_time_after), + "EndTime": serialize.iso8601_datetime(end_time), + "EndTime<": serialize.iso8601_datetime(end_time_before), + "EndTime>": serialize.iso8601_datetime(end_time_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CallPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.api.v2010.account.call.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingList + :returns: Page of CallInstance """ - return self._proxy.recordings + response = self._version.domain.twilio.request("GET", target_url) + return CallPage(self._version, response, solution=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 + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.api.v2010.account.call.notification.NotificationList - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationList + :returns: Page of CallInstance """ - return self._proxy.notifications + response = await self._version.domain.twilio.request_async("GET", target_url) + return CallPage(self._version, response, solution=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..96f3eae3bf --- /dev/null +++ b/twilio/rest/api/v2010/account/call/event.py @@ -0,0 +1,472 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EventInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EventInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 9d64fe1e20..bed0f202c0 100644 --- a/twilio/rest/api/v2010/account/call/notification.py +++ b/twilio/rest/api/v2010/account/call/notification.py @@ -1,503 +1,881 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 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") - def __init__(self, version, account_sid, call_sid): - """ - Initialize the NotificationList + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } - :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._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'], limits['page_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. + return await self._proxy.fetch_async() - :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) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NotificationInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.call.notification.NotificationInstance] + + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream( - log=log, - message_date_before=message_date_before, - message_date=message_date, - message_date_after=message_date_after, - limit=limit, - page_size=page_size, - )) + return self._proxy.fetch_with_http_info() - 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of NotificationInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the NotificationInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - 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, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + return await self._proxy.fetch_with_http_info_async() - return NotificationPage(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 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 str target_url: API-generated URL for the requested results page - :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): + """ + Initialize the NotificationContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call Notification resource to fetch. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the Call Notification resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Call Notification resource to fetch. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 + ) ) - return NotificationPage(self._version, response, self._solution) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - def get(self, sid): + Returns: + tuple: (payload, status_code, headers) """ - Constructs a NotificationContext - :param sid: The unique string that identifies the resource + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.call.notification.NotificationContext - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationContext + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> NotificationInstance: """ - return NotificationContext( + Fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + payload, _, _ = self._fetch() + 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a NotificationContext + Fetch the NotificationInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return NotificationContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class NotificationPage(Page): - """ """ + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + async def fetch_async(self) -> NotificationInstance: """ - Initialize the NotificationPage + Asynchronous coroutine to fetch the NotificationInstance - :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 + :returns: The fetched NotificationInstance """ - super(NotificationPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = await self._fetch_async() + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of NotificationInstance + Asynchronous coroutine to fetch the NotificationInstance and return response metadata - :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 + :returns: ApiResponse with instance, status code, and headers """ - return NotificationInstance( + payload, status_code, headers = await self._fetch_async() + instance = 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"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' - - -class NotificationContext(InstanceContext): - """ """ - - def __init__(self, version, account_sid, call_sid, sid): - """ - Initialize the NotificationContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :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 - :returns: twilio.rest.api.v2010.account.call.notification.NotificationContext - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationContext - """ - super(NotificationContext, 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}/Notifications/{sid}.json'.format(**self._solution) +class NotificationPage(Page): - def fetch(self): + def get_instance(self, payload: Dict[str, Any]) -> NotificationInstance: """ - Fetch the NotificationInstance + Build an instance of NotificationInstance - :returns: The fetched NotificationInstance - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationInstance + :param payload: Payload response from the API """ - payload = self._version.fetch(method='GET', uri=self._uri, ) return NotificationInstance( 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"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a 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 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'), - } - - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'call_sid': call_sid, - 'sid': sid or self._properties['sid'], - } +class NotificationList(ListResource): - @property - def _proxy(self): + def __init__(self, version: Version, account_sid: str, call_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 NotificationList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call Notification resources to read. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the Call Notification resources to read. - :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'], + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Notifications.json".format( + **self._solution ) - return self._context + ) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + 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]: """ - return self._properties['account_sid'] + 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. - @property - def api_version(self): - """ - :returns: The API version used to create the Call Notification resource - :rtype: unicode - """ - return self._properties['api_version'] + :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) - @property - def call_sid(self): - """ - :returns: The SID of the Call the resource is associated with - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['call_sid'] + 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"], + ) - @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): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + async def stream_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NotificationInstance]: """ - return self._properties['date_updated'] + 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. - @property - def error_code(self): - """ - :returns: A unique error code corresponding to the notification - :rtype: unicode - """ - return self._properties['error_code'] + :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) - @property - def log(self): - """ - :returns: An integer log level - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['log'] + 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"], + ) - @property - def message_date(self): - """ - :returns: The date the notification was generated - :rtype: datetime - """ - return self._properties['message_date'] + return self._version.stream_async(page, limits["limit"]) - @property - def message_text(self): - """ - :returns: The text of the notification - :rtype: unicode + def stream_with_http_info( + 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, + ) -> tuple: """ - return self._properties['message_text'] + Streams NotificationInstance and returns headers from first page - @property - def more_info(self): - """ - :returns: A URL for more information about the error code - :rtype: unicode - """ - return self._properties['more_info'] - @property - def request_method(self): - """ - :returns: HTTP method used with the request url - :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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['request_method'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) - @property - def request_url(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - :returns: URL of the resource that generated the notification - :rtype: unicode + Asynchronously streams NotificationInstance and returns headers from first page + + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['request_url'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) - @property - def request_variables(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - :returns: Twilio-generated HTTP variables sent to the server - :rtype: unicode + Lists NotificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NotificationInstance]: + """ + Asynchronously lists NotificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists NotificationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists NotificationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['request_variables'] + Retrieve a single page of NotificationInstance records from the API. + Request is executed immediately - @property - def response_body(self): + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NotificationInstance """ - :returns: The HTTP body returned by your server - :rtype: unicode + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NotificationPage(self._version, response, solution=self._solution) + + async def page_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NotificationPage: + """ + Asynchronously retrieve a single page of NotificationInstance records from the API. + Request is executed immediately + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NotificationInstance """ - return self._properties['response_body'] + 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 response_headers(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 NotificationPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NotificationPage, status code, and headers + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = NotificationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NotificationPage, status code, and headers + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = NotificationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> NotificationPage: """ - :returns: The HTTP headers returned by your server - :rtype: unicode + 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['response_headers'] + response = self._version.domain.twilio.request("GET", target_url) + return NotificationPage(self._version, response, solution=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, solution=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..1d203e8521 100644 --- a/twilio/rest/api/v2010/account/call/payment.py +++ b/twilio/rest/api/v2010/account/call/payment.py @@ -1,399 +1,919 @@ -# 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.api_response import ApiResponse 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): + + class BankAccountType(object): + CONSUMER_CHECKING = "consumer-checking" + CONSUMER_SAVINGS = "consumer-savings" + COMMERCIAL_CHECKING = "commercial-checking" + + class Capture(object): + PAYMENT_CARD_NUMBER = "payment-card-number" + EXPIRATION_DATE = "expiration-date" + SECURITY_CODE = "security-code" + POSTAL_CODE = "postal-code" + BANK_ROUTING_NUMBER = "bank-routing-number" + BANK_ACCOUNT_NUMBER = "bank-account-number" + PAYMENT_CARD_NUMBER_MATCHER = "payment-card-number-matcher" + EXPIRATION_DATE_MATCHER = "expiration-date-matcher" + SECURITY_CODE_MATCHER = "security-code-matcher" + POSTAL_CODE_MATCHER = "postal-code-matcher" + + class PaymentMethod(object): + CREDIT_CARD = "credit-card" + ACH_DEBIT = "ach-debit" + + class Status(object): + COMPLETE = "complete" + CANCEL = "cancel" + + class TokenType(object): + ONE_TIME = "one-time" + REUSABLE = "reusable" + PAYMENT_METHOD = "payment-method" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Payments resource is associated with. This will refer to the call sid that is producing the payment card (credit/ACH) information thru DTMF. + :ivar sid: The SID of the Payments resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } - def __init__(self, version, account_sid, call_sid): + self._context: Optional[PaymentContext] = None + + @property + def _proxy(self) -> "PaymentContext": """ - Initialize the PaymentList + 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 Payments resource. - :param call_sid: The SID of the Call the resource is associated with. + :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 - :returns: twilio.rest.api.v2010.account.call.payment.PaymentList - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentList + def update( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> "PaymentInstance": """ - super(PaymentList, self).__init__(version) + Update the PaymentInstance - # 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): + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: The updated PaymentInstance """ - Create the PaymentInstance + return self._proxy.update( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) - :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. + async def update_async( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> "PaymentInstance": + """ + Asynchronous coroutine to update the PaymentInstance - :returns: The created PaymentInstance - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentInstance - """ - data = values.of({ - 'IdempotencyKey': idempotency_key, - 'StatusCallback': status_callback, - 'BankAccountType': bank_account_type, - 'ChargeAmount': charge_amount, - 'Currency': currency, - 'Description': description, - 'Input': input, - 'MinPostalCodeLength': min_postal_code_length, - 'Parameter': serialize.object(parameter), - 'PaymentConnector': payment_connector, - 'PaymentMethod': payment_method, - 'PostalCode': 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, ) + :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: - return PaymentInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], + :returns: The updated PaymentInstance + """ + return await self._proxy.update_async( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, ) - def get(self, sid): + def update_with_http_info( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> ApiResponse: """ - Constructs a PaymentContext + Update the PaymentInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return PaymentContext( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - sid=sid, + return self._proxy.update_with_http_info( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> ApiResponse: """ - Constructs a PaymentContext + Asynchronous coroutine to update the PaymentInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return PaymentContext( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - sid=sid, + return await self._proxy.update_with_http_info_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, + ) -> tuple: """ - Build an instance of PaymentInstance + Internal helper for update operation - :param dict payload: Payload response from the API + Returns: + tuple: (payload, status_code, headers) + """ - :returns: twilio.rest.api.v2010.account.call.payment.PaymentInstance - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentInstance + data = values.of( + { + "IdempotencyKey": idempotency_key, + "StatusCallback": status_callback, + "Capture": capture, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> PaymentInstance: """ + Update the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: The updated PaymentInstance + """ + payload, _, _ = self._update( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) return PaymentInstance( 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): + def update_with_http_info( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> ApiResponse: """ - Provide a friendly representation + Update the PaymentInstance and return response metadata - :returns: Machine friendly representation - :rtype: str - """ - return '' + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) + instance = PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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. """ + 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, + ) -> tuple: + """ + Internal async helper for update operation - def __init__(self, version, account_sid, call_sid, sid): + Returns: + tuple: (payload, status_code, headers) """ - Initialize the PaymentContext - :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 + data = values.of( + { + "IdempotencyKey": idempotency_key, + "StatusCallback": status_callback, + "Capture": capture, + "Status": status, + } + ) + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.call.payment.PaymentContext - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentContext - """ - super(PaymentContext, self).__init__(version) + headers["Content-Type"] = "application/x-www-form-urlencoded" - # 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) + headers["Accept"] = "application/json" - def update(self, idempotency_key, status_callback, capture=values.unset, - status=values.unset): + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - Update the PaymentInstance + Asynchronous coroutine to update the PaymentInstance - :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. + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: :returns: The updated PaymentInstance - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentInstance """ - data = values.of({ - 'IdempotencyKey': idempotency_key, - 'StatusCallback': status_callback, - 'Capture': capture, - 'Status': status, - }) + payload, _, _ = await self._update_async( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) + return PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PaymentInstance and return response metadata - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :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: - return PaymentInstance( + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 PaymentList(ListResource): - class BankAccountType(object): - CONSUMER_CHECKING = "consumer-checking" - CONSUMER_SAVINGS = "consumer-savings" - COMMERCIAL_CHECKING = "commercial-checking" + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the PaymentList - class TokenType(object): - ONE_TIME = "one-time" - REUSABLE = "reusable" + :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. - 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" + """ + super().__init__(version) - class Status(object): - COMPLETE = "complete" - CANCEL = "cancel" + # 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 __init__(self, version, payload, account_sid, call_sid, sid=None): - """ - Initialize the PaymentInstance + 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, + require_matching_inputs: Union[str, object] = values.unset, + confirmation: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "RequireMatchingInputs": require_matching_inputs, + "Confirmation": confirmation, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: twilio.rest.api.v2010.account.call.payment.PaymentInstance - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentInstance - """ - super(PaymentInstance, self).__init__(version) + headers["Content-Type"] = "application/x-www-form-urlencoded" - # 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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'call_sid': call_sid, - 'sid': sid or self._properties['sid'], - } + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - @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, + require_matching_inputs: Union[str, object] = values.unset, + confirmation: 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` + :param require_matching_inputs: A comma-separated list of payment information fields that require the caller to enter the same value twice for confirmation. Supported values are `payment-card-number`, `expiration-date`, `security-code`, and `postal-code`. + :param confirmation: Whether to prompt the caller to confirm their payment information before submitting to the payment gateway. If `true`, the caller will hear the last 4 digits of their card or account number and must press 1 to confirm or 2 to cancel. Default is `false`. - @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'] + payload, _, _ = self._create( + idempotency_key=idempotency_key, + status_callback=status_callback, + bank_account_type=bank_account_type, + charge_amount=charge_amount, + currency=currency, + description=description, + input=input, + min_postal_code_length=min_postal_code_length, + parameter=parameter, + payment_connector=payment_connector, + payment_method=payment_method, + postal_code=postal_code, + security_code=security_code, + timeout=timeout, + token_type=token_type, + valid_card_types=valid_card_types, + require_matching_inputs=require_matching_inputs, + confirmation=confirmation, + ) + return PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) - @property - def call_sid(self): - """ - :returns: The SID of the Call the resource is associated with. - :rtype: unicode - """ - return self._properties['call_sid'] + def create_with_http_info( + 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, + require_matching_inputs: Union[str, object] = values.unset, + confirmation: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the PaymentInstance and return response metadata + + :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` + :param require_matching_inputs: A comma-separated list of payment information fields that require the caller to enter the same value twice for confirmation. Supported values are `payment-card-number`, `expiration-date`, `security-code`, and `postal-code`. + :param confirmation: Whether to prompt the caller to confirm their payment information before submitting to the payment gateway. If `true`, the caller will hear the last 4 digits of their card or account number and must press 1 to confirm or 2 to cancel. Default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + idempotency_key=idempotency_key, + status_callback=status_callback, + bank_account_type=bank_account_type, + charge_amount=charge_amount, + currency=currency, + description=description, + input=input, + min_postal_code_length=min_postal_code_length, + parameter=parameter, + payment_connector=payment_connector, + payment_method=payment_method, + postal_code=postal_code, + security_code=security_code, + timeout=timeout, + token_type=token_type, + valid_card_types=valid_card_types, + require_matching_inputs=require_matching_inputs, + confirmation=confirmation, + ) + instance = PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + require_matching_inputs: Union[str, object] = values.unset, + confirmation: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "RequireMatchingInputs": require_matching_inputs, + "Confirmation": confirmation, + } + ) + 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'] + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def uri(self): + 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, + require_matching_inputs: Union[str, object] = values.unset, + confirmation: 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` + :param require_matching_inputs: A comma-separated list of payment information fields that require the caller to enter the same value twice for confirmation. Supported values are `payment-card-number`, `expiration-date`, `security-code`, and `postal-code`. + :param confirmation: Whether to prompt the caller to confirm their payment information before submitting to the payment gateway. If `true`, the caller will hear the last 4 digits of their card or account number and must press 1 to confirm or 2 to cancel. Default is `false`. + + :returns: The created PaymentInstance """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + payload, _, _ = await self._create_async( + idempotency_key=idempotency_key, + status_callback=status_callback, + bank_account_type=bank_account_type, + charge_amount=charge_amount, + currency=currency, + description=description, + input=input, + min_postal_code_length=min_postal_code_length, + parameter=parameter, + payment_connector=payment_connector, + payment_method=payment_method, + postal_code=postal_code, + security_code=security_code, + timeout=timeout, + token_type=token_type, + valid_card_types=valid_card_types, + require_matching_inputs=require_matching_inputs, + confirmation=confirmation, + ) + return PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_with_http_info_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, + require_matching_inputs: Union[str, object] = values.unset, + confirmation: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the PaymentInstance and return response metadata + + :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` + :param require_matching_inputs: A comma-separated list of payment information fields that require the caller to enter the same value twice for confirmation. Supported values are `payment-card-number`, `expiration-date`, `security-code`, and `postal-code`. + :param confirmation: Whether to prompt the caller to confirm their payment information before submitting to the payment gateway. If `true`, the caller will hear the last 4 digits of their card or account number and must press 1 to confirm or 2 to cancel. Default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + idempotency_key=idempotency_key, + status_callback=status_callback, + bank_account_type=bank_account_type, + charge_amount=charge_amount, + currency=currency, + description=description, + input=input, + min_postal_code_length=min_postal_code_length, + parameter=parameter, + payment_connector=payment_connector, + payment_method=payment_method, + postal_code=postal_code, + security_code=security_code, + timeout=timeout, + token_type=token_type, + valid_card_types=valid_card_types, + require_matching_inputs=require_matching_inputs, + confirmation=confirmation, + ) + instance = PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 f4bbf8bc51..1e17481856 100644 --- a/twilio/rest/api/v2010/account/call/recording.py +++ b/twilio/rest/api/v2010/account/call/recording.py @@ -1,596 +1,1431 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + + class Source(object): + DIALVERB = "DialVerb" + CONFERENCE = "Conference" + OUTBOUNDAPI = "OutboundAPI" + TRUNKING = "Trunking" + RECORDVERB = "RecordVerb" + STARTCALLRECORDINGAPI = "StartCallRecordingAPI" + STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" + + class Status(object): + IN_PROGRESS = "in-progress" + PAUSED = "paused" + STOPPED = "stopped" + PROCESSING = "processing" + COMPLETED = "completed" + ABSENT = "absent" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resource. + :ivar api_version: The API version used to make the recording. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Recording resource is associated with. + :ivar conference_sid: The Conference SID that identifies the conference associated with the recording, if a conference recording. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar start_time: The start time of the recording in GMT and in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar duration: The length of the recording in seconds. + :ivar sid: The unique string that that we created to identify the Recording resource. + :ivar price: The one-time cost of creating the recording in the `price_unit` currency. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar encryption_details: How to decrypt the recording if it was encrypted using [Call Recording Encryption](https://www.twilio.com/docs/voice/tutorials/voice-recording-encryption) feature. + :ivar price_unit: The currency used in the `price` property. Example: `USD`. + :ivar status: + :ivar channels: The number of channels in the final recording file. Can be: `1`, or `2`. Separating a two leg call into two separate channels of the recording file is supported in [Dial](https://www.twilio.com/docs/voice/twiml/dial#attributes-record) and [Outbound Rest API](https://www.twilio.com/docs/voice/make-calls) record options. + :ivar source: + :ivar error_code: The error code that describes why the recording is `absent`. The error code is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). This value is null if the recording `status` is not `absent`. + :ivar track: The recorded track. Can be: `inbound`, `outbound`, or `both`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.call_sid: Optional[str] = payload.get("call_sid") + self.conference_sid: Optional[str] = payload.get("conference_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.start_time: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("start_time") + ) + self.duration: Optional[str] = payload.get("duration") + self.sid: Optional[str] = payload.get("sid") + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.uri: Optional[str] = payload.get("uri") + self.encryption_details: Optional[Dict[str, object]] = payload.get( + "encryption_details" + ) + self.price_unit: Optional[str] = payload.get("price_unit") + self.status: Optional["RecordingInstance.Status"] = payload.get("status") + self.channels: Optional[int] = deserialize.integer(payload.get("channels")) + self.source: Optional["RecordingInstance.Source"] = payload.get("source") + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.track: Optional[str] = payload.get("track") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } - def __init__(self, version, account_sid, call_sid): + self._context: Optional[RecordingContext] = None + + @property + def _proxy(self) -> "RecordingContext": """ - Initialize the RecordingList + 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 call_sid: The SID of the Call the resource is associated with + :returns: RecordingContext for this RecordingInstance + """ + if self._context is None: + self._context = RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.api.v2010.account.call.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingList + def delete(self) -> bool: """ - super(RecordingList, self).__init__(version) + Deletes the RecordingInstance - # Path Solution - self._solution = {'account_sid': account_sid, 'call_sid': call_sid, } - self._uri = '/Accounts/{account_sid}/Calls/{call_sid}/Recordings.json'.format(**self._solution) - def create(self, recording_status_callback_event=values.unset, - recording_status_callback=values.unset, - recording_status_callback_method=values.unset, trim=values.unset, - recording_channels=values.unset): + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: """ - Create the RecordingInstance + Asynchronous coroutine that deletes 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 - :returns: The created RecordingInstance - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingInstance + :returns: True if delete succeeds, False otherwise """ - 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, - }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance with HTTP info - 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: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance with HTTP info - :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: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.call.recording.RecordingInstance] + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page( - date_created_before=date_created_before, - date_created=date_created, - date_created_after=date_created_after, - page_size=limits['page_size'], - ) + def fetch(self) -> "RecordingInstance": + """ + Fetch the RecordingInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() - :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) + async def fetch_async(self) -> "RecordingInstance": + """ + Asynchronous coroutine to fetch the RecordingInstance - :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 await self._proxy.fetch_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_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of RecordingInstance records from the API. - Request is executed immediately + Fetch the RecordingInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - 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 self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance with HTTP info - return RecordingPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of RecordingInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": + """ + Update the RecordingInstance - :returns: Page of RecordingInstance - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingPage + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + status=status, + pause_behavior=pause_behavior, ) - return RecordingPage(self._version, response, self._solution) + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": + """ + Asynchronous coroutine to update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. - def get(self, sid): + :returns: The updated RecordingInstance """ - Constructs a RecordingContext + return await self._proxy.update_async( + status=status, + pause_behavior=pause_behavior, + ) - :param sid: The unique string that identifies the resource + def update_with_http_info( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RecordingInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers """ - return RecordingContext( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - sid=sid, + return self._proxy.update_with_http_info( + status=status, + pause_behavior=pause_behavior, ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Constructs a RecordingContext + Asynchronous coroutine to update the RecordingInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return RecordingContext( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - sid=sid, + return await self._proxy.update_with_http_info_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, call_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 call_sid: The SID of the Call the resource is associated with + Initialize the RecordingContext - :returns: twilio.rest.api.v2010.account.call.recording.RecordingPage - :rtype: twilio.rest.api.v2010.account.call.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 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(RecordingPage, 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}/Recordings/{sid}.json".format( + **self._solution + ) + ) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of RecordingInstance + Internal helper for delete operation - :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: + tuple: (success_boolean, status_code, headers) """ - return RecordingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers ) - 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 '' + success, _, _ = self._delete() + return success + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance and return response metadata -class RecordingContext(InstanceContext): - """ """ - def __init__(self, version, account_sid, call_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the RecordingContext + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, 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 call_sid: The Call SID of the resource to fetch - :param sid: The unique string that identifies the resource + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation - :returns: twilio.rest.api.v2010.account.call.recording.RecordingContext - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingContext + Returns: + tuple: (success_boolean, status_code, headers) """ - super(RecordingContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'call_sid': call_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Calls/{call_sid}/Recordings/{sid}.json'.format(**self._solution) + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - def update(self, status, pause_behavior=values.unset): + async def delete_async(self) -> bool: """ - Update the RecordingInstance + Asynchronous coroutine that deletes 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. - :returns: The updated RecordingInstance - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'Status': status, 'PauseBehavior': pause_behavior, }) + success, _, _ = await self._delete_async() + return success - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + payload, _, _ = self._fetch() 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Fetch the RecordingInstance + Fetch the RecordingInstance and return response metadata - :returns: The fetched RecordingInstance - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingInstance + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the RecordingInstance + Asynchronous coroutine to fetch the RecordingInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def _update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> tuple: """ - Provide a friendly representation + Internal helper for update operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "Status": status, + "PauseBehavior": pause_behavior, + } + ) + headers = values.of({}) -class RecordingInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - class Status(object): - IN_PROGRESS = "in-progress" - PAUSED = "paused" - STOPPED = "stopped" - PROCESSING = "processing" - COMPLETED = "completed" - ABSENT = "absent" + headers["Accept"] = "application/json" - class Source(object): - DIALVERB = "DialVerb" - CONFERENCE = "Conference" - OUTBOUNDAPI = "OutboundAPI" - TRUNKING = "Trunking" - RECORDVERB = "RecordVerb" - STARTCALLRECORDINGAPI = "StartCallRecordingAPI" - STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - 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')), - } + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Update the RecordingInstance - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'call_sid': call_sid, - 'sid': sid or self._properties['sid'], - } + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. - @property - def _proxy(self): + :returns: The updated RecordingInstance """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, _, _ = self._update(status=status, pause_behavior=pause_behavior) + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) - :returns: RecordingContext for this RecordingInstance - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingContext + def update_with_http_info( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: """ - 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 + Update the RecordingInstance and return response metadata - @property - def account_sid(self): + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, pause_behavior=pause_behavior + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> tuple: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['account_sid'] - @property - def api_version(self): + data = values.of( + { + "Status": status, + "PauseBehavior": pause_behavior, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: """ - :returns: The API version used to make the recording - :rtype: unicode + Asynchronous coroutine to update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance """ - return self._properties['api_version'] + payload, _, _ = await self._update_async( + status=status, pause_behavior=pause_behavior + ) + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) - @property - def call_sid(self): + async def update_with_http_info_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: """ - :returns: The SID of the Call the resource is associated with - :rtype: unicode + Asynchronous coroutine to update the RecordingInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['call_sid'] + payload, status_code, headers = await self._update_async( + status=status, pause_behavior=pause_behavior + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def conference_sid(self): + def __repr__(self) -> str: """ - :returns: The Conference SID that identifies the conference associated with the recording - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['conference_sid'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def date_created(self): + +class RecordingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + Build an instance of RecordingInstance + + :param payload: Payload response from the API """ - return self._properties['date_created'] - @property - def date_updated(self): + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['date_updated'] + return "" - @property - def start_time(self): + +class RecordingList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): """ - :returns: The start time of the recording, given in RFC 2822 format - :rtype: datetime + Initialize the RecordingList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resources to read. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + """ - return self._properties['start_time'] + super().__init__(version) - @property - def duration(self): + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/Recordings.json".format( + **self._solution + ) + + def _create( + self, + recording_status_callback_event: Union[List[str], object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "RecordingConfigurationId": recording_configuration_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + recording_configuration_id: Union[str, object] = values.unset, + ) -> RecordingInstance: """ - :returns: The length of the recording in seconds - :rtype: unicode + 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. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + + :returns: The created RecordingInstance """ - return self._properties['duration'] + payload, _, _ = self._create( + recording_status_callback_event=recording_status_callback_event, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + trim=trim, + recording_channels=recording_channels, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + ) + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) - @property - def sid(self): + def create_with_http_info( + 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, + recording_configuration_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the RecordingInstance and return response metadata + + :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. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + recording_status_callback_event=recording_status_callback_event, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + trim=trim, + recording_channels=recording_channels, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + recording_configuration_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "RecordingConfigurationId": recording_configuration_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + recording_configuration_id: 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. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + + :returns: The created RecordingInstance """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = await self._create_async( + recording_status_callback_event=recording_status_callback_event, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + trim=trim, + recording_channels=recording_channels, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + ) + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_with_http_info_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, + recording_configuration_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the RecordingInstance and return response metadata + + :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. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + recording_status_callback_event=recording_status_callback_event, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + trim=trim, + recording_channels=recording_channels, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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['sid'] + 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(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 one-time cost of creating the recording. - :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'] + 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 uri(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 URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: """ - return self._properties['uri'] + Streams RecordingInstance and returns headers from first page - @property - def encryption_details(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: How to decrypt the recording. - :rtype: dict + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - return self._properties['encryption_details'] + Asynchronously streams RecordingInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The currency used in the price property. - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: """ - return self._properties['price_unit'] + Lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def status(self): + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: """ - :returns: The status of the recording - :rtype: RecordingInstance.Status + Asynchronously lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['status'] + Lists RecordingInstance and returns headers from first page - @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: ApiResponse with list of instances, status code, and headers """ - :returns: The number of channels in the final recording file - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists RecordingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with RecordingPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with RecordingPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..30ffea6d94 --- /dev/null +++ b/twilio/rest/api/v2010/account/call/siprec.py @@ -0,0 +1,3737 @@ +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.api_response import ApiResponse +from twilio.base.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 update_with_http_info( + self, status: "SiprecInstance.UpdateStatus" + ) -> ApiResponse: + """ + Update the SiprecInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "SiprecInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SiprecInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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") -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, status: "SiprecInstance.UpdateStatus") -> SiprecInstance: + """ + Update the SiprecInstance + + :param status: + + :returns: The updated SiprecInstance + """ + payload, _, _ = self._update(status=status) + return SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, status: "SiprecInstance.UpdateStatus" + ) -> ApiResponse: + """ + Update the SiprecInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, status: "SiprecInstance.UpdateStatus") -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, status: "SiprecInstance.UpdateStatus" + ) -> SiprecInstance: + """ + Asynchronous coroutine to update the SiprecInstance + + :param status: + + :returns: The updated SiprecInstance + """ + payload, _, _ = await self._update_async(status=status) + return SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, status: "SiprecInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SiprecInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=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, + ) + return SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the SiprecInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=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, + ) + instance = SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=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, + ) + return SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the SiprecInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=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, + ) + instance = SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..99338e0663 --- /dev/null +++ b/twilio/rest/api/v2010/account/call/stream.py @@ -0,0 +1,3739 @@ +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.api_response import ApiResponse +from twilio.base.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 update_with_http_info( + self, status: "StreamInstance.UpdateStatus" + ) -> ApiResponse: + """ + Update the StreamInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "StreamInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the StreamInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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") -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, status: "StreamInstance.UpdateStatus") -> StreamInstance: + """ + Update the StreamInstance + + :param status: + + :returns: The updated StreamInstance + """ + payload, _, _ = self._update(status=status) + return StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, status: "StreamInstance.UpdateStatus" + ) -> ApiResponse: + """ + Update the StreamInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, status: "StreamInstance.UpdateStatus") -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, status: "StreamInstance.UpdateStatus" + ) -> StreamInstance: + """ + Asynchronous coroutine to update the StreamInstance + + :param status: + + :returns: The updated StreamInstance + """ + payload, _, _ = await self._update_async(status=status) + return StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, status: "StreamInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the StreamInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + url=url, + name=name, + track=track, + status_callback=status_callback, + status_callback_method=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, + ) + return StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the StreamInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + url=url, + name=name, + track=track, + status_callback=status_callback, + status_callback_method=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, + ) + instance = StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + url=url, + name=name, + track=track, + status_callback=status_callback, + status_callback_method=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, + ) + return StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the StreamInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + url=url, + name=name, + track=track, + status_callback=status_callback, + status_callback_method=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, + ) + instance = StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..0d56c61ff3 --- /dev/null +++ b/twilio/rest/api/v2010/account/call/transcription.py @@ -0,0 +1,791 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.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 update_with_http_info( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> ApiResponse: + """ + Update the TranscriptionInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TranscriptionInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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") -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> TranscriptionInstance: + """ + Update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + payload, _, _ = self._update(status=status) + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> ApiResponse: + """ + Update the TranscriptionInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> TranscriptionInstance: + """ + Asynchronous coroutine to update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + payload, _, _ = await self._update_async(status=status) + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TranscriptionInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + conversation_configuration: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + transcription_configuration_id: Union[str, object] = values.unset, + enable_provider_data: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "ConversationConfiguration": conversation_configuration, + "ConversationId": conversation_id, + "TranscriptionConfigurationId": transcription_configuration_id, + "EnableProviderData": serialize.boolean_to_string(enable_provider_data), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + conversation_configuration: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + transcription_configuration_id: Union[str, object] = values.unset, + enable_provider_data: Union[bool, 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 + :param conversation_configuration: The ID of the Conversations Configuration for customizing conversation behavior in Intelligence Service + :param conversation_id: The ID of the Conversation for associating this Transcription with an existing Conversation in Intelligence Service + :param transcription_configuration_id: The ID of the RealTimeTranscription Configuration for configuring all the non-default behaviors in one go. + :param enable_provider_data: Whether the callback includes raw provider data. + + :returns: The created TranscriptionInstance + """ + payload, _, _ = self._create( + 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, + conversation_configuration=conversation_configuration, + conversation_id=conversation_id, + transcription_configuration_id=transcription_configuration_id, + enable_provider_data=enable_provider_data, + ) + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def create_with_http_info( + 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, + conversation_configuration: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + transcription_configuration_id: Union[str, object] = values.unset, + enable_provider_data: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the TranscriptionInstance and return response metadata + + :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 + :param conversation_configuration: The ID of the Conversations Configuration for customizing conversation behavior in Intelligence Service + :param conversation_id: The ID of the Conversation for associating this Transcription with an existing Conversation in Intelligence Service + :param transcription_configuration_id: The ID of the RealTimeTranscription Configuration for configuring all the non-default behaviors in one go. + :param enable_provider_data: Whether the callback includes raw provider data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + 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, + conversation_configuration=conversation_configuration, + conversation_id=conversation_id, + transcription_configuration_id=transcription_configuration_id, + enable_provider_data=enable_provider_data, + ) + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + conversation_configuration: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + transcription_configuration_id: Union[str, object] = values.unset, + enable_provider_data: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "ConversationConfiguration": conversation_configuration, + "ConversationId": conversation_id, + "TranscriptionConfigurationId": transcription_configuration_id, + "EnableProviderData": serialize.boolean_to_string(enable_provider_data), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + conversation_configuration: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + transcription_configuration_id: Union[str, object] = values.unset, + enable_provider_data: Union[bool, 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 + :param conversation_configuration: The ID of the Conversations Configuration for customizing conversation behavior in Intelligence Service + :param conversation_id: The ID of the Conversation for associating this Transcription with an existing Conversation in Intelligence Service + :param transcription_configuration_id: The ID of the RealTimeTranscription Configuration for configuring all the non-default behaviors in one go. + :param enable_provider_data: Whether the callback includes raw provider data. + + :returns: The created TranscriptionInstance + """ + payload, _, _ = await self._create_async( + 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, + conversation_configuration=conversation_configuration, + conversation_id=conversation_id, + transcription_configuration_id=transcription_configuration_id, + enable_provider_data=enable_provider_data, + ) + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_with_http_info_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, + conversation_configuration: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + transcription_configuration_id: Union[str, object] = values.unset, + enable_provider_data: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TranscriptionInstance and return response metadata + + :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 + :param conversation_configuration: The ID of the Conversations Configuration for customizing conversation behavior in Intelligence Service + :param conversation_id: The ID of the Conversation for associating this Transcription with an existing Conversation in Intelligence Service + :param transcription_configuration_id: The ID of the RealTimeTranscription Configuration for configuring all the non-default behaviors in one go. + :param enable_provider_data: Whether the callback includes raw provider data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + 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, + conversation_configuration=conversation_configuration, + conversation_id=conversation_id, + transcription_configuration_id=transcription_configuration_id, + enable_provider_data=enable_provider_data, + ) + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..d1ed0a91ee --- /dev/null +++ b/twilio/rest/api/v2010/account/call/user_defined_message.py @@ -0,0 +1,226 @@ +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.api_response import ApiResponse + +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 + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(content=content, idempotency_key=idempotency_key) + return UserDefinedMessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def create_with_http_info( + self, content: str, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the UserDefinedMessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + content=content, idempotency_key=idempotency_key + ) + instance = UserDefinedMessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, content: str, idempotency_key: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + content=content, idempotency_key=idempotency_key + ) + return UserDefinedMessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_with_http_info_async( + self, content: str, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the UserDefinedMessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + content=content, idempotency_key=idempotency_key + ) + instance = UserDefinedMessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..eea6263faa --- /dev/null +++ b/twilio/rest/api/v2010/account/call/user_defined_message_subscription.py @@ -0,0 +1,444 @@ +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.api_response import ApiResponse +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserDefinedMessageSubscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserDefinedMessageSubscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the UserDefinedMessageSubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserDefinedMessageSubscriptionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserDefinedMessageSubscriptionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + callback=callback, idempotency_key=idempotency_key, method=method + ) + return UserDefinedMessageSubscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def create_with_http_info( + self, + callback: str, + idempotency_key: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the UserDefinedMessageSubscriptionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + callback=callback, idempotency_key=idempotency_key, method=method + ) + instance = UserDefinedMessageSubscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + callback: str, + idempotency_key: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + callback=callback, idempotency_key=idempotency_key, method=method + ) + return UserDefinedMessageSubscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_with_http_info_async( + self, + callback: str, + idempotency_key: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the UserDefinedMessageSubscriptionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + callback=callback, idempotency_key=idempotency_key, method=method + ) + instance = UserDefinedMessageSubscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 ab15a5f385..9edc8ce213 100644 --- a/twilio/rest/api/v2010/account/conference/__init__.py +++ b/twilio/rest/api/v2010/account/conference/__init__.py @@ -1,549 +1,1304 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page from twilio.rest.api.v2010.account.conference.participant import ParticipantList from twilio.rest.api.v2010.account.conference.recording import RecordingList -class ConferenceList(ListResource): - """ """ +class ConferenceInstance(InstanceResource): - def __init__(self, version, account_sid): - """ - Initialize the ConferenceList + class ReasonConferenceEnded(object): + CONFERENCE_ENDED_VIA_API = "conference-ended-via-api" + PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_LEFT = ( + "participant-with-end-conference-on-exit-left" + ) + PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_KICKED = ( + "participant-with-end-conference-on-exit-kicked" + ) + LAST_PARTICIPANT_KICKED = "last-participant-kicked" + LAST_PARTICIPANT_LEFT = "last-participant-left" + + class Status(object): + INIT = "init" + IN_PROGRESS = "in-progress" + COMPLETED = "completed" - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created this resource + class UpdateStatus(object): + COMPLETED = "completed" - :returns: twilio.rest.api.v2010.account.conference.ConferenceList - :rtype: twilio.rest.api.v2010.account.conference.ConferenceList - """ - super(ConferenceList, self).__init__(version) + """ + :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" + ) - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Conferences.json'.format(**self._solution) + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + + self._context: Optional[ConferenceContext] = None - def stream(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, date_updated_before=values.unset, - date_updated=values.unset, date_updated_after=values.unset, - friendly_name=values.unset, status=values.unset, limit=None, - page_size=None): + @property + def _proxy(self) -> "ConferenceContext": """ - Streams ConferenceInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param date date_created_before: 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) + :returns: ConferenceContext for this ConferenceInstance + """ + if self._context is None: + self._context = ConferenceContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.conference.ConferenceInstance] + def fetch(self) -> "ConferenceInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the ConferenceInstance - page = self.page( - date_created_before=date_created_before, - date_created=date_created, - date_created_after=date_created_after, - date_updated_before=date_updated_before, - date_updated=date_updated, - date_updated_after=date_updated_after, - friendly_name=friendly_name, - status=status, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched ConferenceInstance + """ + return self._proxy.fetch() - def list(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, date_updated_before=values.unset, - date_updated=values.unset, date_updated_after=values.unset, - friendly_name=values.unset, status=values.unset, limit=None, - page_size=None): + async def fetch_async(self) -> "ConferenceInstance": """ - Lists ConferenceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine to fetch the ConferenceInstance - :param date date_created_before: 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 await self._proxy.fetch_async() - def page(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, date_updated_before=values.unset, - date_updated=values.unset, date_updated_after=values.unset, - friendly_name=values.unset, status=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of ConferenceInstance records from the API. - Request is executed immediately + Fetch the ConferenceInstance with HTTP info - :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 - :returns: Page of ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferencePage + :returns: ApiResponse with instance, status code, and headers """ - 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, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConferenceInstance with HTTP info - return ConferencePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of ConferenceInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> "ConferenceInstance": + """ + Update the ConferenceInstance - :param 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) + async def update_async( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> "ConferenceInstance": + """ + Asynchronous coroutine to update the ConferenceInstance + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` - def get(self, sid): + :returns: The updated ConferenceInstance """ - Constructs a ConferenceContext + return await self._proxy.update_async( + status=status, + announce_url=announce_url, + announce_method=announce_method, + ) + + def update_with_http_info( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConferenceInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return ConferenceContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + status=status, + announce_url=announce_url, + announce_method=announce_method, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Constructs a ConferenceContext + Asynchronous coroutine to update the ConferenceInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return ConferenceContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + status=status, + announce_url=announce_url, + announce_method=announce_method, + ) - def __repr__(self): + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + return self._proxy.participants + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + return self._proxy.recordings + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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 + ) - def get_instance(self, payload): - """ - Build an instance of ConferenceInstance + self._participants: Optional[ParticipantList] = None + self._recordings: Optional[RecordingList] = None - :param dict payload: Payload response from the API + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.api.v2010.account.conference.ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceInstance + Returns: + tuple: (payload, status_code, headers) """ - return ConferenceInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConferenceInstance: """ - Provide a friendly representation + Fetch the ConferenceInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched ConferenceInstance """ - return '' + payload, _, _ = self._fetch() + return ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConferenceInstance and return response metadata -class ConferenceContext(InstanceContext): - """ """ - def __init__(self, version, account_sid, sid): + :returns: ApiResponse with instance, status code, and headers """ - Initialize the ConferenceContext + payload, status_code, headers = self._fetch() + instance = ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 sid: The unique string that identifies this resource + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: twilio.rest.api.v2010.account.conference.ConferenceContext - :rtype: twilio.rest.api.v2010.account.conference.ConferenceContext + Returns: + tuple: (payload, status_code, headers) """ - super(ConferenceContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Conferences/{sid}.json'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._participants = None - self._recordings = None + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + async def fetch_async(self) -> ConferenceInstance: """ - Fetch the ConferenceInstance + Asynchronous coroutine to fetch the ConferenceInstance + :returns: The fetched ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - + payload, _, _ = await self._fetch_async() 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 fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConferenceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ConferenceInstance: """ Update the ConferenceInstance - :param 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._update( + status=status, announce_url=announce_url, announce_method=announce_method + ) + return ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConferenceInstance and return response metadata - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, announce_url=announce_url, announce_method=announce_method + ) + instance = ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ConferenceInstance: + """ + Asynchronous coroutine to update the ConferenceInstance + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, 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, _, _ = await self._update_async( + status=status, announce_url=announce_url, announce_method=announce_method + ) 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"], ) + async def update_with_http_info_async( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConferenceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, announce_url=announce_url, announce_method=announce_method + ) + instance = ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @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"] + ) - def __init__(self, version, payload, account_sid, sid=None): + def __repr__(self) -> str: """ - Initialize the ConferenceInstance + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.conference.ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceInstance + :returns: Machine friendly representation """ - super(ConferenceInstance, self).__init__(version) + return "" - # Marshaled Properties - self._properties = { - 'account_sid': payload.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'), - } - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } +class ConferenceList(ListResource): - @property - def _proxy(self): + def __init__(self, version: Version, account_sid: str): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Initialize the ConferenceList - :returns: ConferenceContext for this ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceContext - """ - if self._context is None: - self._context = ConferenceContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Conference resource(s) to read. - @property - def account_sid(self): - """ - :returns: The SID of the Account that created this resource - :rtype: unicode """ - return self._properties['account_sid'] + super().__init__(version) - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that this resource was created - :rtype: datetime + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Conferences.json".format(**self._solution) + + def stream( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConferenceInstance]: """ - return self._properties['date_created'] + Streams ConferenceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def api_version(self): - """ - :returns: The API version used to create this conference - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['api_version'] + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + page_size=limits["page_size"], + ) - @property - def friendly_name(self): - """ - :returns: A string that you assigned to describe this conference room - :rtype: unicode - """ - return self._properties['friendly_name'] + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConferenceInstance]: + """ + Asynchronously streams ConferenceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - @property - def region(self): - """ - :returns: A string that represents the Twilio Region where the conference was mixed - :rtype: unicode - """ - return self._properties['region'] + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def sid(self): - """ - :returns: The unique string that identifies this 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( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + page_size=limits["page_size"], + ) - @property - def status(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams ConferenceInstance and returns headers from first page + + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The status of this conference - :rtype: ConferenceInstance.Status + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams ConferenceInstance and returns headers from first page + + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['status'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 + Lists ConferenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConferenceInstance]: + """ + Asynchronously lists ConferenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists ConferenceInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists ConferenceInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['uri'] + Retrieve a single page of ConferenceInstance records from the API. + Request is executed immediately - @property - def subresource_uris(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: A list of related resources identified by their relative URIs - :rtype: unicode + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "DateUpdated": serialize.iso8601_date(date_updated), + "DateUpdated<": serialize.iso8601_date(date_updated_before), + "DateUpdated>": serialize.iso8601_date(date_updated_after), + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConferencePage(self._version, response, solution=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['subresource_uris'] + 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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ConferencePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConferencePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ConferencePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConferencePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 8055c380d3..616cad578a 100644 --- a/twilio/rest/api/v2010/account/conference/participant.py +++ b/twilio/rest/api/v2010/account/conference/participant.py @@ -1,657 +1,668 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class ParticipantList(ListResource): - """ """ +class ParticipantInstance(InstanceResource): - def __init__(self, version, account_sid, conference_sid): - """ - Initialize the ParticipantList + class Status(object): + QUEUED = "queued" + CONNECTING = "connecting" + RINGING = "ringing" + CONNECTED = "connected" + COMPLETE = "complete" + FAILED = "failed" + + """ + :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") - :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 + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + "call_sid": call_sid or self.call_sid, + } - :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantList - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantList - """ - super(ParticipantList, self).__init__(version) + self._context: Optional[ParticipantContext] = None - # Path Solution - self._solution = {'account_sid': account_sid, 'conference_sid': conference_sid, } - self._uri = '/Accounts/{account_sid}/Conferences/{conference_sid}/Participants.json'.format(**self._solution) - - def create(self, from_, to, status_callback=values.unset, - status_callback_method=values.unset, - status_callback_event=values.unset, timeout=values.unset, - record=values.unset, muted=values.unset, beep=values.unset, - start_conference_on_enter=values.unset, - end_conference_on_exit=values.unset, wait_url=values.unset, - wait_method=values.unset, early_media=values.unset, - max_participants=values.unset, conference_record=values.unset, - conference_trim=values.unset, - conference_status_callback=values.unset, - conference_status_callback_method=values.unset, - conference_status_callback_event=values.unset, - recording_channels=values.unset, - recording_status_callback=values.unset, - recording_status_callback_method=values.unset, - sip_auth_username=values.unset, sip_auth_password=values.unset, - region=values.unset, - conference_recording_status_callback=values.unset, - conference_recording_status_callback_method=values.unset, - recording_status_callback_event=values.unset, - conference_recording_status_callback_event=values.unset, - coaching=values.unset, call_sid_to_coach=values.unset, - byoc=values.unset): + @property + def _proxy(self) -> "ParticipantContext": """ - Create the ParticipantInstance + 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 `from` phone number used to invite a participant - :param unicode to: The number, client id, or sip address of the new participant - :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 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 byoc: BYOC trunk SID (Beta) + :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: 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), - '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, - 'Byoc': byoc, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete(self) -> bool: + """ + Deletes the ParticipantInstance - return ParticipantInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - ) - def stream(self, muted=values.unset, hold=values.unset, coaching=values.unset, - limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - Streams ParticipantInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param bool muted: 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) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.conference.participant.ParticipantInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the ParticipantInstance - page = self.page(muted=muted, hold=hold, coaching=coaching, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, muted=values.unset, hold=values.unset, coaching=values.unset, - limit=None, page_size=None): + def delete_with_http_info(self) -> ApiResponse: """ - Lists ParticipantInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the ParticipantInstance with HTTP info - :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) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.conference.participant.ParticipantInstance] + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream( - muted=muted, - hold=hold, - coaching=coaching, - limit=limit, - page_size=page_size, - )) + return self._proxy.delete_with_http_info() - 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 delete_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of ParticipantInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the ParticipantInstance with HTTP info - :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 - :returns: Page of ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantPage + :returns: ApiResponse with success boolean, status code, and headers """ - data = values.of({ - 'Muted': muted, - 'Hold': hold, - 'Coaching': coaching, - '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) + return await self._proxy.delete_with_http_info_async() - def get_page(self, target_url): + def fetch(self) -> "ParticipantInstance": """ - Retrieve a specific page of ParticipantInstance records from the API. - Request is executed immediately + Fetch the ParticipantInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantPage + :returns: The fetched ParticipantInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ParticipantPage(self._version, response, self._solution) + return self._proxy.fetch() - def get(self, call_sid): + async def fetch_async(self) -> "ParticipantInstance": """ - Constructs a ParticipantContext + Asynchronous coroutine to fetch the ParticipantInstance - :param call_sid: The Call SID of the resource 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( - self._version, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - call_sid=call_sid, - ) + return await self._proxy.fetch_async() - def __call__(self, call_sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a ParticipantContext - - :param call_sid: The Call SID of the resource to fetch + Fetch the ParticipantInstance with HTTP info - :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantContext - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantContext - """ - return ParticipantContext( - self._version, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - call_sid=call_sid, - ) - def __repr__(self): + :returns: ApiResponse with instance, status code, and headers """ - Provide a friendly representation + return self._proxy.fetch_with_http_info() - :returns: Machine friendly representation - :rtype: str + async def fetch_with_http_info_async(self) -> ApiResponse: """ - return '' + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info -class ParticipantPage(Page): - """ """ + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() - def __init__(self, version, response, solution): + def update( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> "ParticipantInstance": """ - Initialize the ParticipantPage + Update the ParticipantInstance - :param 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 + :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: twilio.rest.api.v2010.account.conference.participant.ParticipantPage - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantPage + :returns: The updated ParticipantInstance """ - super(ParticipantPage, self).__init__(version, response) + 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, + ) - # Path Solution - self._solution = 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`. - def get_instance(self, payload): + :returns: The updated ParticipantInstance """ - Build an instance of ParticipantInstance + return await self._proxy.update_async( + muted=muted, + hold=hold, + hold_url=hold_url, + hold_method=hold_method, + announce_url=announce_url, + announce_method=announce_method, + wait_url=wait_url, + wait_method=wait_method, + beep_on_exit=beep_on_exit, + end_conference_on_exit=end_conference_on_exit, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + ) - :param dict payload: Payload response from the API + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ParticipantInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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, + ) - :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance - """ - return ParticipantInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + muted=muted, + hold=hold, + hold_url=hold_url, + hold_method=hold_method, + announce_url=announce_url, + announce_method=announce_method, + wait_url=wait_url, + wait_method=wait_method, + beep_on_exit=beep_on_exit, + end_conference_on_exit=end_conference_on_exit, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, ) - def __repr__(self): + 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 ParticipantContext(InstanceContext): - """ """ - def __init__(self, version, account_sid, conference_sid, call_sid): + def __init__( + self, version: Version, account_sid: str, conference_sid: str, call_sid: str + ): """ Initialize the ParticipantContext - :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 of the resource to fetch - - :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantContext - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantContext + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Participant resources to update. + :param conference_sid: The SID of the conference with the participant to update. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID or label of the participant to update. Non URL safe characters in a label must be percent encoded, for example, a space character is represented as %20. """ - super(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, + "call_sid": call_sid, } - self._uri = '/Accounts/{account_sid}/Conferences/{conference_sid}/Participants/{call_sid}.json'.format(**self._solution) - - def fetch(self): - """ - Fetch the ParticipantInstance - - :returns: The fetched ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return ParticipantInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - call_sid=self._solution['call_sid'], + self._uri = "/Accounts/{account_sid}/Conferences/{conference_sid}/Participants/{call_sid}.json".format( + **self._solution ) - 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): + def _delete(self) -> tuple: """ - Update the ParticipantInstance + Internal helper for delete operation - :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` + Returns: + tuple: (success_boolean, status_code, headers) + """ - :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 = values.of({}) - return ParticipantInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - call_sid=self._solution['call_sid'], + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers ) - def delete(self): + def delete(self) -> bool: """ Deletes the ParticipantInstance + :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + success, _, _ = self._delete() + return success - def __repr__(self): + def delete_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Deletes the ParticipantInstance and return response metadata - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) -class ParticipantInstance(InstanceResource): - """ """ + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation - class Status(object): - QUEUED = "queued" - CONNECTING = "connecting" - RINGING = "ringing" - CONNECTED = "connected" - COMPLETE = "complete" - FAILED = "failed" + Returns: + tuple: (success_boolean, status_code, headers) + """ - 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'), - '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'), - } + headers = values.of({}) - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'conference_sid': conference_sid, - 'call_sid': call_sid or self._properties['call_sid'], - } + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - @property - def _proxy(self): + async def delete_async(self) -> bool: """ - 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 that deletes the ParticipantInstance - :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'], - ) - return self._context - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: True if delete succeeds, False otherwise """ - return self._properties['account_sid'] + success, _, _ = await self._delete_async() + return success - @property - def call_sid(self): - """ - :returns: The SID of the Call the resource is associated with - :rtype: unicode + async def delete_with_http_info_async(self) -> ApiResponse: """ - return self._properties['call_sid'] + Asynchronous coroutine that deletes the ParticipantInstance and return response metadata - @property - def call_sid_to_coach(self): - """ - :returns: The SID of the participant who is being `coached` - :rtype: unicode - """ - return self._properties['call_sid_to_coach'] - @property - def coaching(self): + :returns: ApiResponse with success boolean, status code, and headers """ - :returns: Indicates if the participant changed to coach - :rtype: bool - """ - return self._properties['coaching'] + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - @property - def conference_sid(self): + def _fetch(self) -> tuple: """ - :returns: The SID of the conference the participant is in - :rtype: unicode - """ - return self._properties['conference_sid'] + Internal helper for fetch operation - @property - def date_created(self): + Returns: + tuple: (payload, status_code, headers) """ - :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'] + headers = values.of({}) - @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'] + headers["Accept"] = "application/json" - @property - def muted(self): - """ - :returns: Whether the participant is muted - :rtype: bool - """ - return self._properties['muted'] + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - @property - def hold(self): + def fetch(self) -> ParticipantInstance: """ - :returns: Whether the participant is on hold - :rtype: bool - """ - return self._properties['hold'] + Fetch the ParticipantInstance - @property - def start_conference_on_enter(self): - """ - :returns: Whether the conference starts when the participant joins the conference - :rtype: bool + + :returns: The fetched ParticipantInstance """ - return self._properties['start_conference_on_enter'] + payload, _, _ = self._fetch() + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) - @property - def status(self): + def fetch_with_http_info(self) -> ApiResponse: """ - :returns: The status of the participant's call in a session - :rtype: ParticipantInstance.Status + Fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['status'] + payload, status_code, headers = self._fetch() + instance = ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def uri(self): + async def _fetch_async(self) -> tuple: """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['uri'] - def fetch(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ParticipantInstance: """ - Fetch the ParticipantInstance + Asynchronous coroutine to fetch the ParticipantInstance + :returns: The fetched ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance """ - return self._proxy.fetch() + payload, _, _ = await self._fetch_async() + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) - def update(self, muted=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 fetch_with_http_info_async(self) -> ApiResponse: """ - Update the ParticipantInstance + Asynchronous coroutine to fetch the ParticipantInstance and return response metadata - :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` - :returns: The updated ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.update( - muted=muted, - hold=hold, - hold_url=hold_url, - hold_method=hold_method, + payload, status_code, headers = await self._fetch_async() + instance = ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Update the ParticipantInstance + + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: The updated ParticipantInstance + """ + payload, _, _ = self._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, @@ -661,22 +672,1759 @@ def update(self, muted=values.unset, hold=values.unset, hold_url=values.unset, coaching=coaching, call_sid_to_coach=call_sid_to_coach, ) + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ParticipantInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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({}) - def delete(self): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - Deletes the ParticipantInstance + payload, _, _ = await self._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, + ) + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - return self._proxy.delete() + 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, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ParticipantList(ListResource): + + def __init__(self, version: Version, account_sid: str, conference_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Participant resources to read. + :param conference_sid: The SID of the conference with the participants to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + } + self._uri = "/Accounts/{account_sid}/Conferences/{conference_sid}/Participants.json".format( + **self._solution + ) + + def _create( + self, + from_: str, + to: str, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + label: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[List[str], object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + conference_recording_status_callback_event: Union[ + List[str], object + ] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + recording_configuration_id: 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, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "RecordingConfigurationId": recording_configuration_id, + "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, + "ClientNotificationUrl": client_notification_url, + "CallerDisplayName": caller_display_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + recording_configuration_id: 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, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Create the ParticipantInstance + + :param from_: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `from` must also be a phone number. If `to` is sip address, this value of `from` should be a username portion to be used to populate the P-Asserted-Identity header that is passed to the SIP endpoint. + :param to: The phone number, SIP address, Client, TwiML App 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`. TwiML App identifiers are formatted `app:`. [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 recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :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. + :param client_notification_url: The URL that we should use to deliver `push call notification`. + :param caller_display_name: The name that populates the display name in the From header. Must be between 2 and 255 characters. Only applicable for calls to sip address. + + :returns: The created ParticipantInstance + """ + payload, _, _ = self._create( + from_=from_, + to=to, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + label=label, + 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_record=conference_record, + conference_trim=conference_trim, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + region=region, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + conference_recording_status_callback_event=conference_recording_status_callback_event, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + jitter_buffer_size=jitter_buffer_size, + byoc=byoc, + caller_id=caller_id, + call_reason=call_reason, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + time_limit=time_limit, + machine_detection=machine_detection, + 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, + amd_status_callback=amd_status_callback, + amd_status_callback_method=amd_status_callback_method, + trim=trim, + call_token=call_token, + client_notification_url=client_notification_url, + caller_display_name=caller_display_name, + ) + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + def create_with_http_info( + 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, + recording_configuration_id: 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, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ParticipantInstance and return response metadata + + :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, Client, TwiML App 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`. TwiML App identifiers are formatted `app:`. [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 recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :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. + :param client_notification_url: The URL that we should use to deliver `push call notification`. + :param caller_display_name: The name that populates the display name in the From header. Must be between 2 and 255 characters. Only applicable for calls to sip address. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + from_=from_, + to=to, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + label=label, + 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_record=conference_record, + conference_trim=conference_trim, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + region=region, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + conference_recording_status_callback_event=conference_recording_status_callback_event, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + jitter_buffer_size=jitter_buffer_size, + byoc=byoc, + caller_id=caller_id, + call_reason=call_reason, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + time_limit=time_limit, + machine_detection=machine_detection, + 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, + amd_status_callback=amd_status_callback, + amd_status_callback_method=amd_status_callback_method, + trim=trim, + call_token=call_token, + client_notification_url=client_notification_url, + caller_display_name=caller_display_name, + ) + instance = ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + recording_configuration_id: 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, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "RecordingConfigurationId": recording_configuration_id, + "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, + "ClientNotificationUrl": client_notification_url, + "CallerDisplayName": caller_display_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + recording_configuration_id: 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, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: 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, Client, TwiML App 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`. TwiML App identifiers are formatted `app:`. [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 recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :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. + :param client_notification_url: The URL that we should use to deliver `push call notification`. + :param caller_display_name: The name that populates the display name in the From header. Must be between 2 and 255 characters. Only applicable for calls to sip address. + + :returns: The created ParticipantInstance + """ + payload, _, _ = await self._create_async( + from_=from_, + to=to, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + label=label, + 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_record=conference_record, + conference_trim=conference_trim, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + region=region, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + conference_recording_status_callback_event=conference_recording_status_callback_event, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + jitter_buffer_size=jitter_buffer_size, + byoc=byoc, + caller_id=caller_id, + call_reason=call_reason, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + time_limit=time_limit, + machine_detection=machine_detection, + 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, + amd_status_callback=amd_status_callback, + amd_status_callback_method=amd_status_callback_method, + trim=trim, + call_token=call_token, + client_notification_url=client_notification_url, + caller_display_name=caller_display_name, + ) + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + async def create_with_http_info_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, + recording_configuration_id: 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, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ParticipantInstance and return response metadata + + :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, Client, TwiML App 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`. TwiML App identifiers are formatted `app:`. [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 recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :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. + :param client_notification_url: The URL that we should use to deliver `push call notification`. + :param caller_display_name: The name that populates the display name in the From header. Must be between 2 and 255 characters. Only applicable for calls to sip address. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + from_=from_, + to=to, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + label=label, + 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_record=conference_record, + conference_trim=conference_trim, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + region=region, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + conference_recording_status_callback_event=conference_recording_status_callback_event, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + jitter_buffer_size=jitter_buffer_size, + byoc=byoc, + caller_id=caller_id, + call_reason=call_reason, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + time_limit=time_limit, + machine_detection=machine_detection, + 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, + amd_status_callback=amd_status_callback, + amd_status_callback_method=amd_status_callback_method, + trim=trim, + call_token=call_token, + client_notification_url=client_notification_url, + caller_display_name=caller_display_name, + ) + instance = ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: + """ + Streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + muted=muted, hold=hold, coaching=coaching, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: + """ + Asynchronously streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + muted=muted, hold=hold, coaching=coaching, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams ParticipantInstance and returns headers from first page + + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + muted=muted, hold=hold, coaching=coaching, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams ParticipantInstance and returns headers from first page + + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + muted=muted, hold=hold, coaching=coaching, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + muted=muted, + hold=hold, + coaching=coaching, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Asynchronously lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + muted=muted, + hold=hold, + coaching=coaching, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists ParticipantInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + muted=muted, + hold=hold, + coaching=coaching, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + muted=muted, + hold=hold, + coaching=coaching, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "Coaching": serialize.boolean_to_string(coaching), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, solution=self._solution) + + async def page_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "Coaching": serialize.boolean_to_string(coaching), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "Coaching": serialize.boolean_to_string(coaching), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "Coaching": serialize.boolean_to_string(coaching), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, call_sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID or label of the participant to update. Non URL safe characters in a label must be percent encoded, for example, a space character is represented as %20. + """ + return ParticipantContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=call_sid, + ) + + def __call__(self, call_sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID or label of the participant to update. Non URL safe characters in a label must be percent encoded, for example, a space character is represented as %20. + """ + return ParticipantContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=call_sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 4d061be549..cca644f741 100644 --- a/twilio/rest/api/v2010/account/conference/recording.py +++ b/twilio/rest/api/v2010/account/conference/recording.py @@ -1,563 +1,1191 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + + class Source(object): + DIALVERB = "DialVerb" + CONFERENCE = "Conference" + OUTBOUNDAPI = "OutboundAPI" + TRUNKING = "Trunking" + RECORDVERB = "RecordVerb" + STARTCALLRECORDINGAPI = "StartCallRecordingAPI" + STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" + + class Status(object): + IN_PROGRESS = "in-progress" + PAUSED = "paused" + STOPPED = "stopped" + PROCESSING = "processing" + COMPLETED = "completed" + ABSENT = "absent" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Conference Recording resource. + :ivar api_version: The API version used to create the recording. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Conference Recording resource is associated with. + :ivar conference_sid: The Conference SID that identifies the conference associated with the recording. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar start_time: The start time of the recording in GMT and in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar duration: The length of the recording in seconds. + :ivar sid: The unique string that that we created to identify the Conference Recording resource. + :ivar price: The one-time cost of creating the recording in the `price_unit` currency. + :ivar price_unit: The currency used in the `price` property. Example: `USD`. + :ivar status: + :ivar channels: The number of channels in the final recording file. Can be: `1`, or `2`. Separating a two leg call into two separate channels of the recording file is supported in [Dial](https://www.twilio.com/docs/voice/twiml/dial#attributes-record) and [Outbound Rest API](https://www.twilio.com/docs/voice/make-calls) record options. + :ivar source: + :ivar error_code: The error code that describes why the recording is `absent`. The error code is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). This value is null if the recording `status` is not `absent`. + :ivar encryption_details: How to decrypt the recording if it was encrypted using [Call Recording Encryption](https://www.twilio.com/docs/voice/tutorials/voice-recording-encryption) feature. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + conference_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.call_sid: Optional[str] = payload.get("call_sid") + self.conference_sid: Optional[str] = payload.get("conference_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.start_time: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("start_time") + ) + self.duration: Optional[str] = payload.get("duration") + self.sid: Optional[str] = payload.get("sid") + self.price: Optional[str] = payload.get("price") + self.price_unit: Optional[str] = payload.get("price_unit") + self.status: Optional["RecordingInstance.Status"] = payload.get("status") + self.channels: Optional[int] = deserialize.integer(payload.get("channels")) + self.source: Optional["RecordingInstance.Source"] = payload.get("source") + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.encryption_details: Optional[Dict[str, object]] = payload.get( + "encryption_details" + ) + self.uri: Optional[str] = payload.get("uri") - def __init__(self, version, account_sid, conference_sid): + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + "sid": sid or self.sid, + } + + self._context: Optional[RecordingContext] = None + + @property + def _proxy(self) -> "RecordingContext": """ - Initialize the RecordingList + 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 Conference SID that identifies the conference associated with the recording + :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: twilio.rest.api.v2010.account.conference.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingList + def delete(self) -> bool: """ - super(RecordingList, self).__init__(version) + Deletes the RecordingInstance - # Path Solution - self._solution = {'account_sid': account_sid, 'conference_sid': conference_sid, } - self._uri = '/Accounts/{account_sid}/Conferences/{conference_sid}/Recordings.json'.format(**self._solution) - def stream(self, date_created_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. + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + 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. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page( - date_created_before=date_created_before, - date_created=date_created, - date_created_after=date_created_after, - page_size=limits['page_size'], - ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists RecordingInstance 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.delete_with_http_info() - :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) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.conference.recording.RecordingInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - 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_with_http_info_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 + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "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, - }) + Asynchronous coroutine to fetch the RecordingInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return RecordingPage(self._version, response, self._solution) + :returns: The fetched RecordingInstance + """ + return await self._proxy.fetch_async() - def get_page(self, target_url): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a specific page of RecordingInstance records from the API. - Request is executed immediately + Fetch the RecordingInstance with HTTP info - :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": + """ + Update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance """ - 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) + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": + """ + Asynchronous coroutine to update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. - def get(self, sid): + :returns: The updated RecordingInstance """ - Constructs a RecordingContext + return await self._proxy.update_async( + status=status, + pause_behavior=pause_behavior, + ) + + def update_with_http_info( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RecordingInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return RecordingContext( - self._version, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - sid=sid, + return self._proxy.update_with_http_info( + status=status, + pause_behavior=pause_behavior, ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Constructs a RecordingContext + Asynchronous coroutine to update the RecordingInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return RecordingContext( - self._version, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - sid=sid, + return await self._proxy.update_with_http_info_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) -> tuple: """ - Build an instance of RecordingInstance + Internal helper for delete operation - :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: + tuple: (success_boolean, status_code, headers) """ - return RecordingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers ) - 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 '' + success, _, _ = self._delete() + return success + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance and return response metadata -class RecordingContext(InstanceContext): - """ """ - def __init__(self, version, account_sid, conference_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the RecordingContext + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, 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 conference_sid: Fetch by unique Conference SID for the recording - :param sid: The unique string that identifies the resource + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation - :returns: twilio.rest.api.v2010.account.conference.recording.RecordingContext - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingContext + Returns: + tuple: (success_boolean, status_code, headers) """ - 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({}) - def update(self, status, pause_behavior=values.unset): + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - Update the RecordingInstance + Asynchronous coroutine that deletes the RecordingInstance - :param RecordingInstance.Status status: The new status of the recording - :param unicode pause_behavior: Whether to record during a pause - :returns: The updated RecordingInstance - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'Status': status, 'PauseBehavior': pause_behavior, }) + success, _, _ = await self._delete_async() + return success - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance and return response metadata - return RecordingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - sid=self._solution['sid'], + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) - def fetch(self): + def fetch(self) -> RecordingInstance: """ Fetch the RecordingInstance + :returns: The fetched RecordingInstance - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - + payload, _, _ = self._fetch() 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 fetch_with_http_info(self) -> ApiResponse: """ - Deletes the RecordingInstance + Fetch the RecordingInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = self._fetch() + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) -class RecordingInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - class Status(object): - IN_PROGRESS = "in-progress" - PAUSED = "paused" - STOPPED = "stopped" - PROCESSING = "processing" - COMPLETED = "completed" - ABSENT = "absent" + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - class Source(object): - DIALVERB = "DialVerb" - CONFERENCE = "Conference" - OUTBOUNDAPI = "OutboundAPI" - TRUNKING = "Trunking" - RECORDVERB = "RecordVerb" - STARTCALLRECORDINGAPI = "StartCallRecordingAPI" - STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance - 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'), - } - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'conference_sid': conference_sid, - 'sid': sid or self._properties['sid'], - } + :returns: The fetched RecordingInstance + """ + payload, _, _ = await self._fetch_async() + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) - @property - def _proxy(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - 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 fetch the RecordingInstance and return response metadata - :returns: RecordingContext for this RecordingInstance - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingContext + + :returns: ApiResponse with instance, status code, and headers """ - 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 + payload, status_code, headers = await self._fetch_async() + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def account_sid(self): + def _update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> tuple: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['account_sid'] - @property - def api_version(self): + data = values.of( + { + "Status": status, + "PauseBehavior": pause_behavior, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: """ - :returns: The API version used to create the recording - :rtype: unicode + Update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance """ - return self._properties['api_version'] + payload, _, _ = self._update(status=status, pause_behavior=pause_behavior) + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) - @property - def call_sid(self): + def update_with_http_info( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: """ - :returns: The SID of the Call the resource is associated with - :rtype: unicode + Update the RecordingInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['call_sid'] + payload, status_code, headers = self._update( + status=status, pause_behavior=pause_behavior + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def conference_sid(self): + async def _update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> tuple: """ - :returns: The Conference SID that identifies the conference associated with the recording - :rtype: unicode + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['conference_sid'] - @property - def date_created(self): + data = values.of( + { + "Status": status, + "PauseBehavior": pause_behavior, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + Asynchronous coroutine to update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance """ - return self._properties['date_created'] + payload, _, _ = await self._update_async( + status=status, pause_behavior=pause_behavior + ) + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) - @property - def date_updated(self): + async def update_with_http_info_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + Asynchronous coroutine to update the RecordingInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['date_updated'] + payload, status_code, headers = await self._update_async( + status=status, pause_behavior=pause_behavior + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def start_time(self): + def __repr__(self) -> str: """ - :returns: The start time of the recording, given in RFC 2822 format - :rtype: datetime + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['start_time'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def duration(self): + +class RecordingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: """ - :returns: The length of the recording in seconds - :rtype: unicode + Build an instance of RecordingInstance + + :param payload: Payload response from the API """ - return self._properties['duration'] - @property - def sid(self): + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + def __repr__(self) -> str: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['sid'] + return "" - @property - def price(self): + +class RecordingList(ListResource): + + def __init__(self, version: Version, account_sid: str, conference_sid: str): """ - :returns: The one-time cost of creating the recording. - :rtype: unicode + Initialize the RecordingList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Conference Recording resources to read. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to read. + """ - return self._properties['price'] + super().__init__(version) - @property - def price_unit(self): + # Path Solution + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + } + self._uri = "/Accounts/{account_sid}/Conferences/{conference_sid}/Recordings.json".format( + **self._solution + ) + + def stream( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RecordingInstance]: """ - :returns: The currency used in the price property. - :rtype: unicode + Streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['price_unit'] + 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 status(self): + 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]: """ - :returns: The status of the recording - :rtype: RecordingInstance.Status + Asynchronously streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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, + page_size=limits["page_size"], + ) - @property - def channels(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: """ - :returns: The number of channels in the final recording file as an integer - :rtype: unicode + Streams RecordingInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['channels'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) - @property - def source(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - :returns: How the recording was created - :rtype: RecordingInstance.Source + Asynchronously streams RecordingInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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['source'] + 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 error_code(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: More information about why the recording is missing, if status is `absent`. - :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 list_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['error_code'] + Lists RecordingInstance and returns headers from first page - @property - def encryption_details(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: ApiResponse with list of instances, status code, and headers """ - :returns: How to decrypt the recording. - :rtype: dict + generator, status_code, headers = self.stream_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists RecordingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['encryption_details'] + Retrieve a single page of RecordingInstance records from the API. + Request is executed immediately - @property - def uri(self): + :param date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, solution=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['uri'] + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with RecordingPage, status code, and headers + """ + 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, + } + ) - def update(self, status, pause_behavior=values.unset): + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with RecordingPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> RecordingPage: """ - Update the RecordingInstance + 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 = self._version.domain.twilio.request("GET", target_url) + return RecordingPage(self._version, response, solution=self._solution) - def fetch(self): + async def get_page_async(self, target_url: str) -> RecordingPage: """ - Fetch the RecordingInstance + Asynchronously retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately - :returns: The fetched RecordingInstance - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance """ - return self._proxy.fetch() + response = await self._version.domain.twilio.request_async("GET", target_url) + return RecordingPage(self._version, response, solution=self._solution) - def delete(self): + def get(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 __call__(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The Twilio-provided string that uniquely identifies the Conference Recording resource to update. Use `Twilio.CURRENT` to reference the current active recording. + """ + return RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 58b0ce72b7..6f6f0513c1 100644 --- a/twilio/rest/api/v2010/account/connect_app.py +++ b/twilio/rest/api/v2010/account/connect_app.py @@ -1,478 +1,1217 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +class ConnectAppInstance(InstanceResource): - def __init__(self, version, account_sid): - """ - Initialize the ConnectAppList + class Permission(object): + GET_ALL = "get-all" + POST_ALL = "post-all" - :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 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") - :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppList - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppList + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + + self._context: Optional[ConnectAppContext] = None + + @property + def _proxy(self) -> "ConnectAppContext": """ - super(ConnectAppList, 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}/ConnectApps.json'.format(**self._solution) + :returns: ConnectAppContext for this ConnectAppInstance + """ + if self._context is None: + self._context = ConnectAppContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def delete(self) -> bool: """ - 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. + Deletes the ConnectAppInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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 """ - 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 ConnectAppInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - Lists ConnectAppInstance 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConnectAppInstance with HTTP info - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.delete_with_http_info() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of ConnectAppInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the ConnectAppInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with success boolean, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.delete_with_http_info_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def fetch(self) -> "ConnectAppInstance": + """ + Fetch the ConnectAppInstance - return ConnectAppPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched ConnectAppInstance """ - Retrieve a specific page of ConnectAppInstance records from the API. - Request is executed immediately + return self._proxy.fetch() - :param str target_url: API-generated URL for the requested results page + async def fetch_async(self) -> "ConnectAppInstance": + """ + Asynchronous coroutine to fetch the ConnectAppInstance - :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 await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConnectAppInstance with HTTP info - return ConnectAppPage(self._version, response, self._solution) - def get(self, sid): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a ConnectAppContext + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConnectAppInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return ConnectAppContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.fetch_with_http_info_async() - def __call__(self, sid): + def update( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> "ConnectAppInstance": """ - Constructs a ConnectAppContext + Update the ConnectAppInstance + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: The updated ConnectAppInstance + """ + return self._proxy.update( + authorize_redirect_url=authorize_redirect_url, + company_name=company_name, + deauthorize_callback_method=deauthorize_callback_method, + deauthorize_callback_url=deauthorize_callback_url, + description=description, + friendly_name=friendly_name, + homepage_url=homepage_url, + permissions=permissions, + ) - :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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ConnectAppInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + authorize_redirect_url=authorize_redirect_url, + company_name=company_name, + deauthorize_callback_method=deauthorize_callback_method, + deauthorize_callback_url=deauthorize_callback_url, + description=description, + friendly_name=friendly_name, + homepage_url=homepage_url, + permissions=permissions, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConnectAppInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: """ - Build an instance of ConnectAppInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance + def delete(self) -> bool: """ - return ConnectAppInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Deletes the ConnectAppInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the ConnectAppInstance and return response metadata -class ConnectAppContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, account_sid, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the ConnectAppContext - :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 + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppContext - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(ConnectAppContext, self).__init__(version) + Asynchronous coroutine that deletes the ConnectAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectAppInstance and return response metadata - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/ConnectApps/{sid}.json'.format(**self._solution) - def fetch(self): + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConnectAppInstance: """ 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, ) + payload, _, _ = self._fetch() + return ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConnectAppInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConnectAppInstance: + """ + Asynchronous coroutine to fetch the ConnectAppInstance + + + :returns: The fetched ConnectAppInstance + """ + payload, _, _ = await self._fetch_async() 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"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConnectAppInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" - 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): + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._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 ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ConnectAppInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> ConnectAppInstance: + """ + Asynchronous coroutine to update the ConnectAppInstance + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: The updated ConnectAppInstance + """ + payload, _, _ = await self._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, + ) 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): + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConnectAppInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - Deletes the ConnectAppInstance + 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 ConnectAppPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConnectAppInstance: + """ + Build an instance of ConnectAppInstance + + :param payload: Payload response from the API """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def __repr__(self): + return ConnectAppInstance( + 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 ConnectAppInstance(InstanceResource): - """ """ - - class Permission(object): - GET_ALL = "get-all" - POST_ALL = "post-all" +class ConnectAppList(ListResource): - def __init__(self, version, payload, account_sid, sid=None): + def __init__(self, version: Version, account_sid: str): """ - Initialize the ConnectAppInstance + 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. - :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance """ - super(ConnectAppInstance, self).__init__(version) + super().__init__(version) - # 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'), + # Path Solution + self._solution = { + "account_sid": account_sid, } + self._uri = "/Accounts/{account_sid}/ConnectApps.json".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConnectAppInstance]: + """ + Streams ConnectAppInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - # Context - self._context = None - self._solution = {'account_sid': account_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: ConnectAppContext for this ConnectAppInstance - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppContext + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConnectAppInstance]: """ - if self._context is None: - self._context = ConnectAppContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + 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 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 = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['account_sid'] + Streams ConnectAppInstance and returns headers from first page - @property - def authorize_redirect_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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The URL to redirect the user to after authorization - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['authorize_redirect_url'] + Asynchronously streams ConnectAppInstance and returns headers from first page - @property - def company_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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The company name set for the Connect App - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectAppInstance]: """ - return self._properties['company_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 deauthorize_callback_method(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 HTTP method we use to call deauthorize_callback_url - :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['deauthorize_callback_method'] + 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 deauthorize_callback_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 we call to de-authorize the Connect App - :rtype: unicode + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['deauthorize_callback_url'] + Lists ConnectAppInstance and returns headers from first page - @property - def description(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: ApiResponse with list of instances, status code, and headers """ - :returns: The description of the Connect App - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['description'] + Asynchronously lists ConnectAppInstance and returns headers from first page - @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: ApiResponse with list of instances, status code, and headers """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['friendly_name'] + Retrieve a single page of ConnectAppInstance records from the API. + Request is executed immediately - @property - def homepage_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 ConnectAppInstance """ - :returns: The URL users can obtain more information - :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, solution=self._solution) + + async def 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['homepage_url'] + Asynchronously retrieve a single page of ConnectAppInstance records from the API. + Request is executed immediately - @property - def permissions(self): + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectAppInstance """ - :returns: The set of permissions that your ConnectApp requests - :rtype: ConnectAppInstance.Permission + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectAppPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['permissions'] + Retrieve a single page with response metadata - @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: ApiResponse with ConnectAppPage, status code, and headers """ - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConnectAppPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['sid'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with ConnectAppPage, status code, and headers """ - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConnectAppPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 + + :param target_url: API-generated URL for the requested results page - def fetch(self): + :returns: Page of ConnectAppInstance """ - Fetch the ConnectAppInstance + response = self._version.domain.twilio.request("GET", target_url) + return ConnectAppPage(self._version, response, solution=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, solution=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 39ee904976..948519d653 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py @@ -1,941 +1,2475 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): + + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" + + class EmergencyAddressStatus(object): + REGISTERED = "registered" + UNREGISTERED = "unregistered" + PENDING_REGISTRATION = "pending-registration" + REGISTRATION_FAILURE = "registration-failure" + PENDING_UNREGISTRATION = "pending-unregistration" + UNREGISTRATION_FAILURE = "unregistration-failure" + + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" + + class VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this IncomingPhoneNumber resource. + :ivar address_sid: The SID of the Address resource associated with the phone number. + :ivar address_requirements: + :ivar api_version: The API version used to start a new TwiML session. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar identity_sid: The SID of the Identity resource that we associate with the phone number. Some regions require an Identity to meet local regulations. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar origin: The phone number's origin. `twilio` identifies Twilio-owned phone numbers and `hosted` identifies hosted phone numbers. + :ivar sid: The unique string that that we created to identify this IncomingPhoneNumber resource. + :ivar sms_application_sid: The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call when the phone number receives an incoming SMS message. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar trunk_sid: The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar voice_receive_mode: + :ivar voice_application_sid: The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_url: The URL we call when the phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + :ivar emergency_status: + :ivar emergency_address_sid: The SID of the emergency address configuration that we use for emergency calling from this phone number. + :ivar emergency_address_status: + :ivar bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :ivar status: + :ivar type: The phone number type. + """ + + 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.type: Optional[str] = payload.get("type") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + + self._context: Optional[IncomingPhoneNumberContext] = None - def __init__(self, version, account_sid): + @property + def _proxy(self) -> "IncomingPhoneNumberContext": """ - Initialize the IncomingPhoneNumberList + 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 + :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: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberList + def delete(self) -> bool: """ - super(IncomingPhoneNumberList, self).__init__(version) + Deletes the IncomingPhoneNumberInstance - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/IncomingPhoneNumbers.json'.format(**self._solution) - # Components - self._local = None - self._mobile = None - self._toll_free = None + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def stream(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: """ - 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. + 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. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - page_size=limits['page_size'], - ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IncomingPhoneNumberInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists IncomingPhoneNumberInstance 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.delete_with_http_info() - :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) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IncomingPhoneNumberInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - 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_with_http_info_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 - - :param str target_url: API-generated URL for the requested results page + return await self._proxy.fetch_async() - :returns: Page of IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return IncomingPhoneNumberPage(self._version, response, self._solution) - - 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Create the IncomingPhoneNumberInstance + Fetch the IncomingPhoneNumberInstance with HTTP info - :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, ) + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() - return IncomingPhoneNumberInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IncomingPhoneNumberInstance with HTTP info - @property - def local(self): + + :returns: ApiResponse with instance, status code, and headers """ - Access the local + return await self._proxy.fetch_with_http_info_async() - :returns: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalList + 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": """ - if self._local is None: - self._local = LocalList(self._version, account_sid=self._solution['account_sid'], ) - return self._local + Update the IncomingPhoneNumberInstance - @property - def mobile(self): + :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 """ - 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, + ) - :returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList + async def update_async( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> "IncomingPhoneNumberInstance": + """ + Asynchronous coroutine to update the IncomingPhoneNumberInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The updated IncomingPhoneNumberInstance """ - if self._mobile is None: - self._mobile = MobileList(self._version, account_sid=self._solution['account_sid'], ) - return self._mobile + 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, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the IncomingPhoneNumberInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + account_sid=account_sid, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + identity_sid=identity_sid, + address_sid=address_sid, + bundle_sid=bundle_sid, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IncomingPhoneNumberInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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 toll_free(self): + def assigned_add_ons(self) -> AssignedAddOnList: """ - Access the toll_free + Access the assigned_add_ons + """ + return self._proxy.assigned_add_ons - :returns: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeList + def __repr__(self) -> str: """ - if self._toll_free is None: - self._toll_free = TollFreeList(self._version, account_sid=self._solution['account_sid'], ) - return self._toll_free + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a IncomingPhoneNumberContext + 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 IncomingPhoneNumberContext(InstanceContext): - :returns: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberContext - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberContext + def __init__(self, version: Version, account_sid: str, sid: str): """ - return IncomingPhoneNumberContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + Initialize the IncomingPhoneNumberContext - 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 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 __repr__(self): + def _delete(self) -> tuple: """ - Provide a friendly representation + Internal helper for delete operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (success_boolean, status_code, headers) """ - return '' + headers = values.of({}) -class IncomingPhoneNumberPage(Page): - """ """ + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def delete(self) -> bool: """ - Initialize the IncomingPhoneNumberPage + Deletes 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: True if delete succeeds, False otherwise """ - super(IncomingPhoneNumberPage, self).__init__(version, response) + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IncomingPhoneNumberInstance and return response metadata - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: ApiResponse with success boolean, status code, and headers """ - Build an instance of IncomingPhoneNumberInstance + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation - :returns: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - return IncomingPhoneNumberInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + 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 '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IncomingPhoneNumberInstance and return response metadata -class IncomingPhoneNumberContext(InstanceContext): - """ """ - def __init__(self, version, account_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the IncomingPhoneNumberContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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 - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberContext - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberContext + def _fetch(self) -> tuple: """ - super(IncomingPhoneNumberContext, self).__init__(version) + Internal helper for fetch operation - # 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): + Returns: + tuple: (payload, status_code, headers) """ - 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 + headers = values.of({}) - :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, ) + headers["Accept"] = "application/json" - return IncomingPhoneNumberInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) - def fetch(self): + def fetch(self) -> IncomingPhoneNumberInstance: """ Fetch the IncomingPhoneNumberInstance + :returns: The fetched IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - + payload, _, _ = self._fetch() 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Deletes the IncomingPhoneNumberInstance + Fetch the IncomingPhoneNumberInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = self._fetch() + instance = IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def assigned_add_ons(self): + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> IncomingPhoneNumberInstance: + """ + Asynchronous coroutine to fetch the IncomingPhoneNumberInstance + + + :returns: The fetched IncomingPhoneNumberInstance + """ + payload, _, _ = await self._fetch_async() + return IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IncomingPhoneNumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> IncomingPhoneNumberInstance: + """ + Update the IncomingPhoneNumberInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The updated IncomingPhoneNumberInstance + """ + payload, _, _ = self._update( + account_sid=account_sid, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + identity_sid=identity_sid, + address_sid=address_sid, + bundle_sid=bundle_sid, + ) + return IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the IncomingPhoneNumberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> IncomingPhoneNumberInstance: + """ + Asynchronous coroutine to update the IncomingPhoneNumberInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The updated IncomingPhoneNumberInstance + """ + payload, _, _ = await self._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, + ) + return IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IncomingPhoneNumberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def assigned_add_ons(self) -> AssignedAddOnList: """ Access the assigned_add_ons + """ + if self._assigned_add_ons is None: + self._assigned_add_ons = AssignedAddOnList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._assigned_add_ons + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IncomingPhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IncomingPhoneNumberInstance: + """ + Build an instance of IncomingPhoneNumberInstance + + :param payload: Payload response from the API + """ + + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class IncomingPhoneNumberList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the IncomingPhoneNumberList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resources to read. + + """ + super().__init__(version) - :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 + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers.json".format( + **self._solution + ) + + self._local: Optional[LocalList] = None + self._mobile: Optional[MobileList] = None + self._toll_free: Optional[TollFreeList] = None + + def _create( + self, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + area_code: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + "PhoneNumber": phone_number, + "AreaCode": area_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + area_code: Union[str, object] = values.unset, + ) -> IncomingPhoneNumberInstance: + """ + Create the IncomingPhoneNumberInstance + + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the new phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param area_code: The desired area code for your new incoming phone number. Can be any three-digit, US or Canada area code. We will provision an available phone number within this area code for you. **You must provide an `area_code` or a `phone_number`.** (US and Canada only). + + :returns: The created IncomingPhoneNumberInstance + """ + payload, _, _ = self._create( + 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, + identity_sid=identity_sid, + address_sid=address_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + phone_number=phone_number, + area_code=area_code, + ) + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the IncomingPhoneNumberInstance and return response metadata + + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the new phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param area_code: The desired area code for your new incoming phone number. Can be any three-digit, US or Canada area code. We will provision an available phone number within this area code for you. **You must provide an `area_code` or a `phone_number`.** (US and Canada only). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + 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, + identity_sid=identity_sid, + address_sid=address_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + phone_number=phone_number, + area_code=area_code, + ) + instance = IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + "PhoneNumber": phone_number, + "AreaCode": area_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + area_code: Union[str, object] = values.unset, + ) -> IncomingPhoneNumberInstance: + """ + Asynchronously create the IncomingPhoneNumberInstance + + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the new phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param area_code: The desired area code for your new incoming phone number. Can be any three-digit, US or Canada area code. We will provision an available phone number within this area code for you. **You must provide an `area_code` or a `phone_number`.** (US and Canada only). + + :returns: The created IncomingPhoneNumberInstance + """ + payload, _, _ = await self._create_async( + 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, + identity_sid=identity_sid, + address_sid=address_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + phone_number=phone_number, + area_code=area_code, + ) + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the IncomingPhoneNumberInstance and return response metadata + + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the new phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param area_code: The desired area code for your new incoming phone number. Can be any three-digit, US or Canada area code. We will provision an available phone number within this area code for you. **You must provide an `area_code` or a `phone_number`.** (US and Canada only). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + 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, + identity_sid=identity_sid, + address_sid=address_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + phone_number=phone_number, + area_code=area_code, + ) + instance = IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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]: """ - 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'], - ) - return self._assigned_add_ons + 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. - def __repr__(self): - """ - Provide a friendly representation + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - :returns: 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( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + return self._version.stream(page, limits["limit"]) -class IncomingPhoneNumberInstance(InstanceResource): - """ """ + async def stream_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IncomingPhoneNumberInstance]: + """ + Asynchronously streams IncomingPhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - class AddressRequirement(object): - NONE = "none" - ANY = "any" - LOCAL = "local" - FOREIGN = "foreign" + :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) - class EmergencyStatus(object): - ACTIVE = "Active" - INACTIVE = "Inactive" + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) - class VoiceReceiveMode(object): - VOICE = "voice" - FAX = "fax" + return self._version.stream_async(page, limits["limit"]) - 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_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'), - } + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams IncomingPhoneNumberInstance and returns headers from first page - # 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 + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - :returns: IncomingPhoneNumberContext for this IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberContext + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - if self._context is None: - self._context = IncomingPhoneNumberContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + 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'] + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - @property - def address_sid(self): - """ - :returns: The SID of the Address resource associated with the phone number - :rtype: unicode + async def stream_with_http_info_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, + ) -> tuple: """ - return self._properties['address_sid'] + Asynchronously streams IncomingPhoneNumberInstance and returns headers from first page - @property - def address_requirements(self): - """ - :returns: Whether the phone number requires an Address registered with Twilio. - :rtype: IncomingPhoneNumberInstance.AddressRequirement - """ - return self._properties['address_requirements'] - @property - def api_version(self): - """ - :returns: The API version used to start a new TwiML session - :rtype: unicode - """ - return self._properties['api_version'] + :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 beta(self): - """ - :returns: Whether the phone number is new to the Twilio platform - :rtype: bool + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['beta'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) - @property - def capabilities(self): - """ - :returns: Indicate if a phone can receive calls or messages - :rtype: unicode - """ - return self._properties['capabilities'] + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - @property - def date_created(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 RFC 2822 date and time in GMT that the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + 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 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 bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ) - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] + async def list_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IncomingPhoneNumberInstance]: + """ + Asynchronously lists IncomingPhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def identity_sid(self): - """ - :returns: The SID of the Identity resource associated with number - :rtype: unicode + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists IncomingPhoneNumberInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists IncomingPhoneNumberInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['identity_sid'] + Retrieve a single page of IncomingPhoneNumberInstance records from the API. + Request is executed immediately - @property - def phone_number(self): - """ - :returns: The phone number in E.164 format - :rtype: unicode - """ - return self._properties['phone_number'] + :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 - @property - def origin(self): - """ - :returns: The phone number's origin. Can be twilio or hosted. - :rtype: unicode + :returns: Page of IncomingPhoneNumberInstance """ - return self._properties['origin'] + 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 sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @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'] + headers["Accept"] = "application/json" - @property - def sms_fallback_method(self): - """ - :returns: The HTTP method used with sms_fallback_url - :rtype: unicode - """ - return self._properties['sms_fallback_method'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IncomingPhoneNumberPage(self._version, response, solution=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 - @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 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 - @property - def sms_method(self): - """ - :returns: The HTTP method to use with sms_url - :rtype: unicode + :returns: Page of IncomingPhoneNumberInstance """ - 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IncomingPhoneNumberPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with IncomingPhoneNumberPage, status code, and headers + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def trunk_sid(self): - """ - :returns: The SID of the Trunk that handles calls to the phone number - :rtype: unicode - """ - return self._properties['trunk_sid'] + headers = values.of({"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 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'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IncomingPhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with IncomingPhoneNumberPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IncomingPhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def voice_method(self): + def get_page(self, target_url: str) -> IncomingPhoneNumberPage: """ - :returns: The HTTP method used with the voice_url - :rtype: unicode - """ - return self._properties['voice_method'] + Retrieve a specific page of IncomingPhoneNumberInstance 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 + :param target_url: API-generated URL for the requested results page + + :returns: Page of IncomingPhoneNumberInstance """ - return self._properties['voice_url'] + response = self._version.domain.twilio.request("GET", target_url) + return IncomingPhoneNumberPage(self._version, response, solution=self._solution) - @property - def emergency_status(self): + async def get_page_async(self, target_url: str) -> IncomingPhoneNumberPage: """ - :returns: Whether the phone number is enabled for emergency calling - :rtype: IncomingPhoneNumberInstance.EmergencyStatus + 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_status'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return IncomingPhoneNumberPage(self._version, response, solution=self._solution) @property - def emergency_address_sid(self): + def local(self) -> LocalList: """ - :returns: The emergency address configuration to use for emergency calling - :rtype: unicode + Access the local """ - return self._properties['emergency_address_sid'] + if self._local is None: + self._local = LocalList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._local @property - def bundle_sid(self): - """ - :returns: The SID of the Bundle resource associated with number - :rtype: unicode - """ - return self._properties['bundle_sid'] - - def update(self, account_sid=values.unset, api_version=values.unset, - friendly_name=values.unset, sms_application_sid=values.unset, - sms_fallback_method=values.unset, sms_fallback_url=values.unset, - sms_method=values.unset, sms_url=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - voice_application_sid=values.unset, - voice_caller_id_lookup=values.unset, - voice_fallback_method=values.unset, voice_fallback_url=values.unset, - voice_method=values.unset, voice_url=values.unset, - emergency_status=values.unset, emergency_address_sid=values.unset, - trunk_sid=values.unset, voice_receive_mode=values.unset, - identity_sid=values.unset, address_sid=values.unset, - 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 79c4b5975f..83acaedda3 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,965 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -from twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension import AssignedAddOnExtensionList +from twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension import ( + AssignedAddOnExtensionList, +) -class AssignedAddOnList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class AssignedAddOnInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + :ivar resource_sid: The SID of the Phone Number to which the Add-on is assigned. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar description: A short description of the functionality that the Add-on provides. + :ivar configuration: A JSON string that represents the current configuration of this Add-on installation. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar subresource_uris: A list of related resources identified by their relative URIs. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + resource_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.resource_sid: Optional[str] = payload.get("resource_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.unique_name: Optional[str] = payload.get("unique_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + "sid": sid or self.sid, + } + + self._context: Optional[AssignedAddOnContext] = None - def __init__(self, version, account_sid, resource_sid): + @property + def _proxy(self) -> "AssignedAddOnContext": """ - Initialize the AssignedAddOnList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param account_sid: The 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. + 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 AssignedAddOnInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnInstance] + + :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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssignedAddOnInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists AssignedAddOnInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssignedAddOnInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "AssignedAddOnInstance": """ - Retrieve a single page of AssignedAddOnInstance records from the API. - Request is executed immediately + 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 self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "AssignedAddOnInstance": + """ + Asynchronous coroutine to fetch the AssignedAddOnInstance - return AssignedAddOnPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched AssignedAddOnInstance """ - Retrieve a specific page of AssignedAddOnInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssignedAddOnInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssignedAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + @property + def extensions(self) -> AssignedAddOnExtensionList: + """ + Access the extensions + """ + return self._proxy.extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssignedAddOnContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, resource_sid: str, sid: str): + """ + Initialize the AssignedAddOnContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource to fetch. + :param resource_sid: The SID of the Phone Number to which the Add-on is assigned. + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. """ - 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) -> tuple: """ - Create the AssignedAddOnInstance + Internal helper for delete operation - :param unicode installed_add_on_sid: The SID that identifies the Add-on installation + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: The created AssignedAddOnInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnInstance + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - data = values.of({'InstalledAddOnSid': installed_add_on_sid, }) + Deletes the AssignedAddOnInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssignedAddOnInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssignedAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssignedAddOnInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AssignedAddOnInstance: + """ + Fetch the AssignedAddOnInstance + + + :returns: The fetched AssignedAddOnInstance + """ + payload, _, _ = self._fetch() 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"], + sid=self._solution["sid"], ) - def get(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a AssignedAddOnContext + Fetch the AssignedAddOnInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return AssignedAddOnContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __call__(self, sid): + async def _fetch_async(self) -> tuple: """ - Constructs a AssignedAddOnContext - - :param sid: The unique string that identifies the resource + Internal async helper for fetch operation - :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: + tuple: (payload, status_code, headers) """ - return AssignedAddOnContext( - self._version, - account_sid=self._solution['account_sid'], - resource_sid=self._solution['resource_sid'], - sid=sid, + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers ) - 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 '' + payload, _, _ = await self._fetch_async() + return AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=self._solution["sid"], + ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssignedAddOnInstance and return response metadata -class AssignedAddOnPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, response, solution): + :returns: ApiResponse with instance, status code, and headers """ - Initialize the AssignedAddOnPage + payload, status_code, headers = await self._fetch_async() + instance = AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 the resource - :param resource_sid: The SID of the Phone Number that installed this Add-on + @property + def extensions(self) -> AssignedAddOnExtensionList: + """ + Access the extensions + """ + if self._extensions is None: + self._extensions = AssignedAddOnExtensionList( + self._version, + self._solution["account_sid"], + self._solution["resource_sid"], + self._solution["sid"], + ) + return self._extensions - :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 + def __repr__(self) -> str: """ - super(AssignedAddOnPage, 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 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) + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns.json".format( + **self._solution + ) - # Dependents - self._extensions = None + def _create(self, installed_add_on_sid: str) -> tuple: + """ + Internal helper for create operation - def fetch(self): + Returns: + tuple: (payload, status_code, headers) """ - Fetch the AssignedAddOnInstance - :returns: The fetched AssignedAddOnInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnInstance + data = values.of( + { + "InstalledAddOnSid": installed_add_on_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, installed_add_on_sid: str) -> AssignedAddOnInstance: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Create the AssignedAddOnInstance + + :param installed_add_on_sid: The SID that identifies the Add-on installation. + :returns: The created AssignedAddOnInstance + """ + payload, _, _ = self._create(installed_add_on_sid=installed_add_on_sid) 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): + def create_with_http_info(self, installed_add_on_sid: str) -> ApiResponse: """ - Deletes the AssignedAddOnInstance + Create the AssignedAddOnInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param installed_add_on_sid: The SID that identifies the Add-on installation. + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = self._create( + installed_add_on_sid=installed_add_on_sid + ) + instance = AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def extensions(self): + async def _create_async(self, installed_add_on_sid: str) -> tuple: """ - Access the extensions + Internal async helper for create operation - :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 + Returns: + tuple: (payload, status_code, headers) """ - 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 - def __repr__(self): + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, installed_add_on_sid: str) -> AssignedAddOnInstance: """ - Provide a friendly representation + Asynchronously create the AssignedAddOnInstance - :returns: Machine friendly representation - :rtype: str + :param installed_add_on_sid: The SID that identifies the Add-on installation. + + :returns: The created AssignedAddOnInstance """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + payload, _, _ = await self._create_async( + installed_add_on_sid=installed_add_on_sid + ) + return AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + ) + async def create_with_http_info_async( + self, installed_add_on_sid: str + ) -> ApiResponse: + """ + Asynchronously create the AssignedAddOnInstance and return response metadata -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'), - } + :param installed_add_on_sid: The SID that identifies the Add-on installation. - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'resource_sid': resource_sid, - 'sid': sid or self._properties['sid'], - } + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + installed_add_on_sid=installed_add_on_sid + ) + instance = AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssignedAddOnInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = AssignedAddOnContext( - self._version, - account_sid=self._solution['account_sid'], - resource_sid=self._solution['resource_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[AssignedAddOnInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Asynchronously streams AssignedAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Streams AssignedAddOnInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def resource_sid(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Phone Number that installed this Add-on - :rtype: unicode + Asynchronously streams AssignedAddOnInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['resource_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def friendly_name(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnInstance]: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Lists AssignedAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['friendly_name'] - @property - def description(self): + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnInstance]: """ - :returns: A short description of the Add-on functionality - :rtype: unicode + Asynchronously lists AssignedAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['description'] - @property - def configuration(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: A JSON string that represents the current configuration - :rtype: dict + Lists AssignedAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['configuration'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def unique_name(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + Asynchronously lists AssignedAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['unique_name'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> AssignedAddOnPage: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + 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['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 AssignedAddOnPage(self._version, response, solution=self._solution) + + async def 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 RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + 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['date_updated'] + 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 AssignedAddOnPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssignedAddOnPage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssignedAddOnPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: A list of related resources identified by their relative URIs - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssignedAddOnPage, status code, and headers """ - return self._properties['subresource_uris'] + data = values.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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssignedAddOnPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> AssignedAddOnPage: """ - Fetch the AssignedAddOnInstance + 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 = self._version.domain.twilio.request("GET", target_url) + return AssignedAddOnPage(self._version, response, solution=self._solution) - def delete(self): + async def get_page_async(self, target_url: str) -> AssignedAddOnPage: """ - Deletes the AssignedAddOnInstance + Asynchronously retrieve a specific page of AssignedAddOnInstance 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 AssignedAddOnInstance """ - return self._proxy.delete() + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssignedAddOnPage(self._version, response, solution=self._solution) - @property - def extensions(self): + def get(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 __call__(self, sid: str) -> AssignedAddOnContext: + """ + Constructs a AssignedAddOnContext + + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. + """ + return AssignedAddOnContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 d6a6dab9b3..f9d3e5d83d 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,743 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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. """ +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") - def __init__(self, version, account_sid, resource_sid, assigned_add_on_sid): - """ - Initialize the AssignedAddOnExtensionList + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + "assigned_add_on_sid": assigned_add_on_sid, + "sid": sid or self.sid, + } - :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 + self._context: Optional[AssignedAddOnExtensionContext] = None - :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 + @property + def _proxy(self) -> "AssignedAddOnExtensionContext": """ - super(AssignedAddOnExtensionList, 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, - 'resource_sid': resource_sid, - 'assigned_add_on_sid': assigned_add_on_sid, - } - self._uri = '/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns/{assigned_add_on_sid}/Extensions.json'.format(**self._solution) + :returns: AssignedAddOnExtensionContext for this AssignedAddOnExtensionInstance + """ + if self._context is None: + self._context = AssignedAddOnExtensionContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def fetch(self) -> "AssignedAddOnExtensionInstance": """ - Streams AssignedAddOnExtensionInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Fetch the AssignedAddOnExtensionInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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 """ - 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) -> "AssignedAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the AssignedAddOnExtensionInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssignedAddOnExtensionInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch_with_http_info() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of AssignedAddOnExtensionInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the AssignedAddOnExtensionInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of AssignedAddOnExtensionInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionPage + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_with_http_info_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return AssignedAddOnExtensionPage(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 AssignedAddOnExtensionInstance 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 AssignedAddOnExtensionInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionPage +class AssignedAddOnExtensionContext(InstanceContext): + + def __init__( + self, + version: Version, + account_sid: str, + resource_sid: str, + assigned_add_on_sid: str, + sid: str, + ): + """ + Initialize the AssignedAddOnExtensionContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource to fetch. + :param resource_sid: The SID of the Phone Number to which the Add-on is assigned. + :param assigned_add_on_sid: The SID that uniquely identifies the assigned Add-on installation. + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + "assigned_add_on_sid": assigned_add_on_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns/{assigned_add_on_sid}/Extensions/{sid}.json".format( + **self._solution ) - return AssignedAddOnExtensionPage(self._version, response, self._solution) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - def get(self, sid): + Returns: + tuple: (payload, status_code, headers) """ - Constructs a AssignedAddOnExtensionContext - :param sid: The unique string that identifies the resource + headers = values.of({}) - :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 + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AssignedAddOnExtensionInstance: """ - return AssignedAddOnExtensionContext( + Fetch the AssignedAddOnExtensionInstance + + + :returns: The fetched AssignedAddOnExtensionInstance + """ + payload, _, _ = self._fetch() + 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a AssignedAddOnExtensionContext + Fetch the AssignedAddOnExtensionInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return AssignedAddOnExtensionContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class AssignedAddOnExtensionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + async def fetch_async(self) -> AssignedAddOnExtensionInstance: """ - Initialize the AssignedAddOnExtensionPage + Asynchronous coroutine to fetch the AssignedAddOnExtensionInstance - :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 + :returns: The fetched AssignedAddOnExtensionInstance + """ + payload, _, _ = await self._fetch_async() + return AssignedAddOnExtensionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: """ - super(AssignedAddOnExtensionPage, self).__init__(version, response) + Asynchronous coroutine to fetch the AssignedAddOnExtensionInstance and return response metadata - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of AssignedAddOnExtensionInstance + payload, status_code, headers = await self._fetch_async() + instance = 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"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + def __repr__(self) -> str: + """ + Provide a friendly representation - :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 + :returns: Machine friendly representation """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssignedAddOnExtensionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssignedAddOnExtensionInstance: + """ + Build an instance of AssignedAddOnExtensionInstance + + :param payload: Payload response from the API + """ + return AssignedAddOnExtensionInstance( self._version, payload, - account_sid=self._solution['account_sid'], - resource_sid=self._solution['resource_sid'], - assigned_add_on_sid=self._solution['assigned_add_on_sid'], + 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) + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns/{assigned_add_on_sid}/Extensions.json".format( + **self._solution + ) - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssignedAddOnExtensionInstance]: """ - Fetch the AssignedAddOnExtensionInstance + Streams AssignedAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :returns: The fetched AssignedAddOnExtensionInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 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'], - ) + 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[AssignedAddOnExtensionInstance]: """ - Provide a friendly representation + 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. - :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 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'), - } + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AssignedAddOnExtensionInstance and returns headers from first page - # 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'], - } - @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: tuple of (generator, status_code, headers) where generator yields instances """ - 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_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: AssignedAddOnExtensionContext for this AssignedAddOnExtensionInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionContext + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - 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'], + Asynchronously streams AssignedAddOnExtensionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnExtensionInstance]: + """ + Lists AssignedAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - 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 + Asynchronously lists AssignedAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['sid'] - @property - def account_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Lists AssignedAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['account_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def resource_sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Phone Number to which the Add-on is assigned - :rtype: unicode + Asynchronously lists AssignedAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['resource_sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def assigned_add_on_sid(self): + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssignedAddOnExtensionPage: """ - :returns: The SID that uniquely identifies the assigned Add-on installation - :rtype: unicode + 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['assigned_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 AssignedAddOnExtensionPage( + self._version, response, solution=self._solution + ) + + async def 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: The string that you assigned to describe the resource - :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['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 AssignedAddOnExtensionPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: A string that you assigned to describe the Product this Extension is used within - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssignedAddOnExtensionPage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssignedAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssignedAddOnExtensionPage, status code, and headers """ - return self._properties['unique_name'] + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssignedAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> AssignedAddOnExtensionPage: """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :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['uri'] + response = self._version.domain.twilio.request("GET", target_url) + return AssignedAddOnExtensionPage( + self._version, response, solution=self._solution + ) - @property - def enabled(self): + async def get_page_async(self, target_url: str) -> AssignedAddOnExtensionPage: """ - :returns: Whether the Extension will be invoked - :rtype: bool + 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['enabled'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssignedAddOnExtensionPage( + self._version, response, solution=self._solution + ) - def fetch(self): + def get(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 __call__(self, sid: str) -> AssignedAddOnExtensionContext: + """ + Constructs a AssignedAddOnExtensionContext + + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. + """ + return AssignedAddOnExtensionContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 f06fe4d645..06ce14ba9f 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,1212 @@ -# 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.api_response import ApiResponse + from twilio.base.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): - """ """ +class LocalInstance(InstanceResource): - def __init__(self, version, account_sid): - """ - Initialize the LocalList + 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.local.LocalList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalList - """ - super(LocalList, self).__init__(version) + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/IncomingPhoneNumbers/Local.json'.format(**self._solution) + class VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" - 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. + """ + :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, + } - :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) + def __repr__(self) -> str: + """ + 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] + :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( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) +class LocalPage(Page): - def list(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): + def get_instance(self, payload: Dict[str, Any]) -> LocalInstance: """ - Lists LocalInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param bool beta: Whether to include 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) + Build an instance of LocalInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.local.LocalInstance] + :param payload: Payload response from the API """ - return list(self.stream( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - limit=limit, - page_size=page_size, - )) - def page(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of LocalInstance records from the API. - Request is executed immediately + return LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - :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 + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of LocalInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalPage + :returns: Machine friendly representation """ - data = values.of({ - 'Beta': beta, - 'FriendlyName': friendly_name, - 'PhoneNumber': phone_number, - 'Origin': origin, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return "" - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return LocalPage(self._version, response, self._solution) +class LocalList(ListResource): - def get_page(self, target_url): + def __init__(self, version: Version, account_sid: str): """ - Retrieve a specific page of LocalInstance records from the API. - Request is executed immediately + Initialize the LocalList - :param str target_url: API-generated URL for the requested results page + :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: Page of LocalInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalPage """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/Local.json".format( + **self._solution + ) + + def _create( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union["LocalInstance.EmergencyStatus", object] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "LocalInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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"}) - return LocalPage(self._version, response, self._solution) + headers["Content-Type"] = "application/x-www-form-urlencoded" - 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): + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union["LocalInstance.EmergencyStatus", object] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "LocalInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> LocalInstance: """ Create the LocalInstance - :param 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 + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. :returns: The created LocalInstance - :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): """ - Provide a friendly representation + payload, _, _ = self._create( + phone_number=phone_number, + 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, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + return LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - :returns: Machine friendly representation - :rtype: str - """ - return '' + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the LocalInstance and return response metadata + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + 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, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 LocalPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the LocalPage + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, 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 the resource + async def create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union["LocalInstance.EmergencyStatus", object] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "LocalInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> LocalInstance: + """ + Asynchronously create the LocalInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - :returns: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalPage - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalPage + :returns: The created LocalInstance """ - super(LocalPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = await self._create_async( + phone_number=phone_number, + 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, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + return LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - def get_instance(self, payload): + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the LocalInstance and return response metadata + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + 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, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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]: """ - Build an instance of 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 dict payload: Payload response from the API + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - :returns: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalInstance + :returns: Generator that will yield up to limit results """ - return LocalInstance(self._version, payload, account_sid=self._solution['account_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"], + ) - 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, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[LocalInstance]: """ - return '' - + 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. -class LocalInstance(InstanceResource): - """ """ + :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) - class AddressRequirement(object): - NONE = "none" - ANY = "any" - LOCAL = "local" - FOREIGN = "foreign" + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) - class EmergencyStatus(object): - ACTIVE = "Active" - INACTIVE = "Inactive" + return self._version.stream_async(page, limits["limit"]) - class VoiceReceiveMode(object): - VOICE = "voice" - FAX = "fax" + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams LocalInstance and returns headers from first page - def __init__(self, version, payload, account_sid): - """ - Initialize the LocalInstance - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalInstance - """ - super(LocalInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.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'), - } - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) - @property - def address_sid(self): - """ - :returns: The SID of the Address resource associated with the phone number - :rtype: unicode - """ - return self._properties['address_sid'] + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - @property - def address_requirements(self): - """ - :returns: Whether the phone number requires an Address registered with Twilio. - :rtype: LocalInstance.AddressRequirement + async def stream_with_http_info_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, + ) -> tuple: """ - return self._properties['address_requirements'] + Asynchronously streams LocalInstance and returns headers from first page - @property - def api_version(self): - """ - :returns: The API version used to start a new TwiML session - :rtype: unicode - """ - return self._properties['api_version'] - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: Indicate if a phone can receive calls or messages - :rtype: unicode - """ - return self._properties['capabilities'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + 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'] + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + 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 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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + 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 identity_sid(self): - """ - :returns: The SID of the Identity resource associated with number - :rtype: unicode - """ - return self._properties['identity_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 phone_number(self): - """ - :returns: The phone number in E.164 format - :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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists LocalInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists LocalInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['phone_number'] + Retrieve a single page of LocalInstance records from the API. + Request is executed immediately - @property - def origin(self): - """ - :returns: The phone number's origin. Can be twilio or hosted. - :rtype: unicode - """ - return self._properties['origin'] + :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 sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: Page of LocalInstance """ - return self._properties['sid'] + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def sms_application_sid(self): - """ - :returns: The SID of the Application resource to handle SMS messages - :rtype: unicode - """ - return self._properties['sms_application_sid'] + 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["Accept"] = "application/json" - @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'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LocalPage(self._version, response, solution=self._solution) + + async def page_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LocalPage: + """ + Asynchronously retrieve a single page of LocalInstance records from the API. + Request is executed immediately - @property - def sms_method(self): - """ - :returns: The HTTP method to use with sms_url - :rtype: unicode - """ - return self._properties['sms_method'] + :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_url(self): - """ - :returns: The URL we call when the phone number receives an incoming SMS message - :rtype: unicode + :returns: Page of LocalInstance """ - return self._properties['sms_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 status_callback(self): - """ - :returns: The URL to send status information to your application - :rtype: unicode - """ - return self._properties['status_callback'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def status_callback_method(self): - """ - :returns: The HTTP method we use to call status_callback - :rtype: unicode - """ - return self._properties['status_callback_method'] + headers["Accept"] = "application/json" - @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'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LocalPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with LocalPage, status code, and headers + """ + 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 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 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["Accept"] = "application/json" - @property - def voice_caller_id_lookup(self): - """ - :returns: Whether to lookup the caller's name - :rtype: bool - """ - return self._properties['voice_caller_id_lookup'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = LocalPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with LocalPage, status code, and headers + """ + 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_fallback_method(self): - """ - :returns: The HTTP method used with voice_fallback_url - :rtype: unicode - """ - return self._properties['voice_fallback_method'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @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'] + headers["Accept"] = "application/json" - @property - def voice_method(self): - """ - :returns: The HTTP method used with the voice_url - :rtype: unicode - """ - return self._properties['voice_method'] + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = LocalPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def voice_url(self): + def get_page(self, target_url: str) -> LocalPage: """ - :returns: The URL we call when this phone number receives a call - :rtype: unicode - """ - return self._properties['voice_url'] + Retrieve a specific page of LocalInstance records from the API. + Request is executed immediately - @property - def emergency_status(self): - """ - :returns: Whether the phone number is enabled for emergency calling - :rtype: LocalInstance.EmergencyStatus - """ - return self._properties['emergency_status'] + :param target_url: API-generated URL for the requested results page - @property - def emergency_address_sid(self): - """ - :returns: The emergency address configuration to use for emergency calling - :rtype: unicode + :returns: Page of LocalInstance """ - return self._properties['emergency_address_sid'] + response = self._version.domain.twilio.request("GET", target_url) + return LocalPage(self._version, response, solution=self._solution) - @property - def bundle_sid(self): + async def get_page_async(self, target_url: str) -> LocalPage: """ - :returns: The SID of the Bundle resource associated with number - :rtype: unicode + 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 """ - return self._properties['bundle_sid'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return LocalPage(self._version, response, solution=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 96f504ad07..2087c91ae3 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,1224 @@ -# 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.api_response import ApiResponse + from twilio.base.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): - """ """ +class MobileInstance(InstanceResource): - def __init__(self, version, account_sid): - """ - Initialize the MobileList + 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.mobile.MobileList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList - """ - super(MobileList, self).__init__(version) + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/IncomingPhoneNumbers/Mobile.json'.format(**self._solution) + class VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" - 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. + """ + :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, + } - :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) + def __repr__(self) -> str: + """ + 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] + :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( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) +class MobilePage(Page): - def list(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): + def get_instance(self, payload: Dict[str, Any]) -> MobileInstance: """ - Lists MobileInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param bool beta: Whether to include 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) + Build an instance of MobileInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance] + :param payload: Payload response from the API """ - return list(self.stream( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - limit=limit, - page_size=page_size, - )) - def page(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of MobileInstance records from the API. - Request is executed immediately + return MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - :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 + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of MobileInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobilePage + :returns: Machine friendly representation """ - data = values.of({ - 'Beta': beta, - 'FriendlyName': friendly_name, - 'PhoneNumber': phone_number, - 'Origin': origin, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return "" - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return MobilePage(self._version, response, self._solution) +class MobileList(ListResource): - def get_page(self, target_url): + def __init__(self, version: Version, account_sid: str): """ - Retrieve a specific page of MobileInstance records from the API. - Request is executed immediately + Initialize the MobileList - :param str target_url: API-generated URL for the requested results page + :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: Page of MobileInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobilePage """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/Mobile.json".format( + **self._solution + ) + + def _create( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "MobileInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "MobileInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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"}) - return MobilePage(self._version, response, self._solution) + headers["Content-Type"] = "application/x-www-form-urlencoded" - 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): + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "MobileInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "MobileInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> MobileInstance: """ Create the MobileInstance - :param 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 + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. :returns: The created MobileInstance - :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): """ - Provide a friendly representation + payload, _, _ = self._create( + phone_number=phone_number, + 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, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + return MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - :returns: Machine friendly representation - :rtype: str - """ - return '' + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the MobileInstance and return response metadata + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + 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, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 MobilePage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the MobilePage + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, 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 the resource + async def create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "MobileInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "MobileInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> MobileInstance: + """ + Asynchronously create the MobileInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - :returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobilePage - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobilePage + :returns: The created MobileInstance """ - super(MobilePage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = await self._create_async( + phone_number=phone_number, + 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, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + return MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - def get_instance(self, payload): + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the MobileInstance and return response metadata + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + 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, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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]: """ - Build an instance of 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 dict payload: Payload response from the API + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - :returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance + :returns: Generator that will yield up to limit results """ - return MobileInstance(self._version, payload, account_sid=self._solution['account_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"], + ) - 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, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MobileInstance]: """ - return '' - + 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. -class MobileInstance(InstanceResource): - """ """ + :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) - class AddressRequirement(object): - NONE = "none" - ANY = "any" - LOCAL = "local" - FOREIGN = "foreign" + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) - class EmergencyStatus(object): - ACTIVE = "Active" - INACTIVE = "Inactive" + return self._version.stream_async(page, limits["limit"]) - class VoiceReceiveMode(object): - VOICE = "voice" - FAX = "fax" + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams MobileInstance and returns headers from first page - def __init__(self, version, payload, account_sid): - """ - Initialize the MobileInstance - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance - """ - super(MobileInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.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'), - } - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) - @property - def address_sid(self): - """ - :returns: The SID of the Address resource associated with the phone number - :rtype: unicode - """ - return self._properties['address_sid'] + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - @property - def address_requirements(self): - """ - :returns: Whether the phone number requires an Address registered with Twilio. - :rtype: MobileInstance.AddressRequirement + async def stream_with_http_info_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, + ) -> tuple: """ - return self._properties['address_requirements'] + Asynchronously streams MobileInstance and returns headers from first page - @property - def api_version(self): - """ - :returns: The API version used to start a new TwiML session - :rtype: unicode - """ - return self._properties['api_version'] - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: Indicate if a phone can receive calls or messages - :rtype: unicode - """ - return self._properties['capabilities'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + 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'] + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + 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 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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + 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 identity_sid(self): - """ - :returns: The SID of the Identity resource associated with number - :rtype: unicode - """ - return self._properties['identity_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 phone_number(self): - """ - :returns: The phone number in E.164 format - :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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists MobileInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists MobileInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['phone_number'] + Retrieve a single page of MobileInstance records from the API. + Request is executed immediately - @property - def origin(self): - """ - :returns: The phone number's origin. Can be twilio or hosted. - :rtype: unicode - """ - return self._properties['origin'] + :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 sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: Page of MobileInstance """ - return self._properties['sid'] + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def sms_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'] + 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["Accept"] = "application/json" - @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'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MobilePage(self._version, response, solution=self._solution) + + async def page_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MobilePage: + """ + Asynchronously retrieve a single page of MobileInstance records from the API. + Request is executed immediately - @property - def sms_method(self): - """ - :returns: The HTTP method to use with sms_url - :rtype: unicode - """ - return self._properties['sms_method'] + :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_url(self): - """ - :returns: The URL we call when the phone number receives an incoming SMS message - :rtype: unicode + :returns: Page of MobileInstance """ - return self._properties['sms_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 status_callback(self): - """ - :returns: The URL to send status information to your application - :rtype: unicode - """ - return self._properties['status_callback'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def status_callback_method(self): - """ - :returns: The HTTP method we use to call status_callback - :rtype: unicode - """ - return self._properties['status_callback_method'] + headers["Accept"] = "application/json" - @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'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MobilePage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MobilePage, status code, and headers + """ + 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 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 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["Accept"] = "application/json" - @property - def voice_caller_id_lookup(self): - """ - :returns: Whether to lookup the caller's name - :rtype: bool - """ - return self._properties['voice_caller_id_lookup'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MobilePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MobilePage, status code, and headers + """ + 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_fallback_method(self): - """ - :returns: The HTTP method used with voice_fallback_url - :rtype: unicode - """ - return self._properties['voice_fallback_method'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @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'] + headers["Accept"] = "application/json" - @property - def voice_method(self): - """ - :returns: The HTTP method used with the voice_url - :rtype: unicode - """ - return self._properties['voice_method'] + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MobilePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def voice_url(self): + def get_page(self, target_url: str) -> MobilePage: """ - :returns: The URL we call when the phone number receives a call - :rtype: unicode - """ - return self._properties['voice_url'] + Retrieve a specific page of MobileInstance records from the API. + Request is executed immediately - @property - def emergency_status(self): - """ - :returns: Whether the phone number is enabled for emergency calling - :rtype: MobileInstance.EmergencyStatus - """ - return self._properties['emergency_status'] + :param target_url: API-generated URL for the requested results page - @property - def emergency_address_sid(self): - """ - :returns: The emergency address configuration to use for emergency calling - :rtype: unicode + :returns: Page of MobileInstance """ - return self._properties['emergency_address_sid'] + response = self._version.domain.twilio.request("GET", target_url) + return MobilePage(self._version, response, solution=self._solution) - @property - def bundle_sid(self): + async def get_page_async(self, target_url: str) -> MobilePage: """ - :returns: The SID of the Bundle resource associated with number - :rtype: unicode + 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 """ - return self._properties['bundle_sid'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return MobilePage(self._version, response, solution=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 d3b9fe0afd..c4597aa459 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,1224 @@ -# 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.api_response import ApiResponse + from twilio.base.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): - """ """ +class TollFreeInstance(InstanceResource): - def __init__(self, version, account_sid): - """ - Initialize the TollFreeList + 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.toll_free.TollFreeList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeList - """ - super(TollFreeList, self).__init__(version) + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/IncomingPhoneNumbers/TollFree.json'.format(**self._solution) + class VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" - 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. + """ + :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, + } - :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) + def __repr__(self) -> str: + """ + 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] + :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( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) +class TollFreePage(Page): - def list(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): + def get_instance(self, payload: Dict[str, Any]) -> TollFreeInstance: """ - Lists TollFreeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param bool beta: Whether to include 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) + Build an instance of TollFreeInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeInstance] + :param payload: Payload response from the API """ - return list(self.stream( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - limit=limit, - page_size=page_size, - )) - def page(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of TollFreeInstance records from the API. - Request is executed immediately + return TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - :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 + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of TollFreeInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreePage + :returns: Machine friendly representation """ - data = values.of({ - 'Beta': beta, - 'FriendlyName': friendly_name, - 'PhoneNumber': phone_number, - 'Origin': origin, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return "" - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return TollFreePage(self._version, response, self._solution) +class TollFreeList(ListResource): - def get_page(self, target_url): + def __init__(self, version: Version, account_sid: str): """ - Retrieve a specific page of TollFreeInstance records from the API. - Request is executed immediately + Initialize the TollFreeList - :param str target_url: API-generated URL for the requested results page + :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: Page of TollFreeInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreePage """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/TollFree.json".format( + **self._solution + ) + + def _create( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "TollFreeInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "TollFreeInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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"}) - return TollFreePage(self._version, response, self._solution) + headers["Content-Type"] = "application/x-www-form-urlencoded" - 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): + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "TollFreeInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "TollFreeInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> TollFreeInstance: """ Create the TollFreeInstance - :param 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 + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. :returns: The created TollFreeInstance - :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): """ - Provide a friendly representation + payload, _, _ = self._create( + phone_number=phone_number, + 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, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + return TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - :returns: Machine friendly representation - :rtype: str - """ - return '' + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the TollFreeInstance and return response metadata + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + 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, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 TollFreePage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the TollFreePage + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, 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 the resource + async def create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "TollFreeInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "TollFreeInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> TollFreeInstance: + """ + Asynchronously create the TollFreeInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - :returns: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreePage - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreePage + :returns: The created TollFreeInstance """ - super(TollFreePage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = await self._create_async( + phone_number=phone_number, + 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, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + return TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - def get_instance(self, payload): + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the TollFreeInstance and return response metadata + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + 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, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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]: """ - Build an instance of 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 dict payload: Payload response from the API + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - :returns: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeInstance + :returns: Generator that will yield up to limit results """ - return TollFreeInstance(self._version, payload, account_sid=self._solution['account_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"], + ) - 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, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TollFreeInstance]: """ - return '' - + 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. -class TollFreeInstance(InstanceResource): - """ """ + :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) - class AddressRequirement(object): - NONE = "none" - ANY = "any" - LOCAL = "local" - FOREIGN = "foreign" + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) - class EmergencyStatus(object): - ACTIVE = "Active" - INACTIVE = "Inactive" + return self._version.stream_async(page, limits["limit"]) - class VoiceReceiveMode(object): - VOICE = "voice" - FAX = "fax" + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams TollFreeInstance and returns headers from first page - def __init__(self, version, payload, account_sid): - """ - Initialize the TollFreeInstance - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeInstance - """ - super(TollFreeInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.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'), - } - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) - @property - def address_sid(self): - """ - :returns: The SID of the Address resource associated with the phone number - :rtype: unicode - """ - return self._properties['address_sid'] + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - @property - def address_requirements(self): - """ - :returns: Whether the phone number requires an Address registered with Twilio. - :rtype: TollFreeInstance.AddressRequirement + async def stream_with_http_info_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, + ) -> tuple: """ - return self._properties['address_requirements'] + Asynchronously streams TollFreeInstance and returns headers from first page - @property - def api_version(self): - """ - :returns: The API version used to start a new TwiML session - :rtype: unicode - """ - return self._properties['api_version'] - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: Indicate if a phone can receive calls or messages - :rtype: unicode - """ - return self._properties['capabilities'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + 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'] + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + 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 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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + 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 identity_sid(self): - """ - :returns: The SID of the Identity resource associated with number - :rtype: unicode - """ - return self._properties['identity_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 phone_number(self): - """ - :returns: The phone number in E.164 format - :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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists TollFreeInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists TollFreeInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['phone_number'] + Retrieve a single page of TollFreeInstance records from the API. + Request is executed immediately - @property - def origin(self): - """ - :returns: The phone number's origin. Can be twilio or hosted. - :rtype: unicode - """ - return self._properties['origin'] + :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 sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: Page of TollFreeInstance """ - return self._properties['sid'] + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def sms_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'] + 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["Accept"] = "application/json" - @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'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollFreePage(self._version, response, solution=self._solution) + + async def page_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TollFreePage: + """ + Asynchronously retrieve a single page of TollFreeInstance records from the API. + Request is executed immediately - @property - def sms_method(self): - """ - :returns: The HTTP method to use with sms_url - :rtype: unicode - """ - return self._properties['sms_method'] + :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_url(self): - """ - :returns: The URL we call when the phone number receives an incoming SMS message - :rtype: unicode + :returns: Page of TollFreeInstance """ - return self._properties['sms_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 status_callback(self): - """ - :returns: The URL to send status information to your application - :rtype: unicode - """ - return self._properties['status_callback'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def status_callback_method(self): - """ - :returns: The HTTP method we use to call status_callback - :rtype: unicode - """ - return self._properties['status_callback_method'] + headers["Accept"] = "application/json" - @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'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollFreePage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TollFreePage, status code, and headers + """ + 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 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 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["Accept"] = "application/json" - @property - def voice_caller_id_lookup(self): - """ - :returns: Whether to lookup the caller's name - :rtype: bool - """ - return self._properties['voice_caller_id_lookup'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TollFreePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TollFreePage, status code, and headers + """ + 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_fallback_method(self): - """ - :returns: The HTTP method used with voice_fallback_url - :rtype: unicode - """ - return self._properties['voice_fallback_method'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @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'] + headers["Accept"] = "application/json" - @property - def voice_method(self): - """ - :returns: The HTTP method used with the voice_url - :rtype: unicode - """ - return self._properties['voice_method'] + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TollFreePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def voice_url(self): + def get_page(self, target_url: str) -> TollFreePage: """ - :returns: The URL we call when the phone number receives a call - :rtype: unicode - """ - return self._properties['voice_url'] + Retrieve a specific page of TollFreeInstance records from the API. + Request is executed immediately - @property - def emergency_status(self): - """ - :returns: Whether the phone number is enabled for emergency calling - :rtype: TollFreeInstance.EmergencyStatus - """ - return self._properties['emergency_status'] + :param target_url: API-generated URL for the requested results page - @property - def emergency_address_sid(self): - """ - :returns: The emergency address configuration to use for emergency calling - :rtype: unicode + :returns: Page of TollFreeInstance """ - return self._properties['emergency_address_sid'] + response = self._version.domain.twilio.request("GET", target_url) + return TollFreePage(self._version, response, solution=self._solution) - @property - def bundle_sid(self): + async def get_page_async(self, target_url: str) -> TollFreePage: """ - :returns: The SID of the Bundle resource associated with number - :rtype: unicode + 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 """ - return self._properties['bundle_sid'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return TollFreePage(self._version, response, solution=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 fa4c90e334..2683e7ab3c 100644 --- a/twilio/rest/api/v2010/account/key.py +++ b/twilio/rest/api/v2010/account/key.py @@ -1,371 +1,955 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +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") + ) - def __init__(self, version, account_sid): + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + + self._context: Optional[KeyContext] = None + + @property + def _proxy(self) -> "KeyContext": """ - Initialize the KeyList + 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: KeyContext for this KeyInstance + """ + if self._context is None: + self._context = KeyContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.api.v2010.account.key.KeyList - :rtype: twilio.rest.api.v2010.account.key.KeyList + def delete(self) -> bool: """ - super(KeyList, self).__init__(version) + Deletes the KeyInstance - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Keys.json'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: """ - 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. + Asynchronous coroutine that deletes the KeyInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KeyInstance with HTTP info - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() - def list(self, limit=None, page_size=None): + async def delete_with_http_info_async(self) -> ApiResponse: """ - 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 with HTTP info - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_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, }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "KeyInstance": + """ + Asynchronous coroutine to fetch the KeyInstance - return KeyPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched KeyInstance """ - Retrieve a specific page of KeyInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KeyInstance with HTTP info - :returns: Page of KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyPage + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update(self, friendly_name: Union[str, object] = values.unset) -> "KeyInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Update the KeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated KeyInstance + """ + return self._proxy.update( + friendly_name=friendly_name, ) - return KeyPage(self._version, response, self._solution) + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "KeyInstance": + """ + Asynchronous coroutine to update the KeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - def get(self, sid): + :returns: The updated KeyInstance """ - Constructs a KeyContext + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - :param sid: The unique string that identifies the resource + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the KeyInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers """ - return KeyContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: """ - Constructs a KeyContext + Asynchronous coroutine to update the KeyInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return KeyContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_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) -> tuple: """ - Build an instance of KeyInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.key.KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return KeyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Deletes the KeyInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the KeyInstance and return response metadata -class KeyContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, account_sid, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the KeyContext - :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 + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.key.KeyContext - :rtype: twilio.rest.api.v2010.account.key.KeyContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(KeyContext, self).__init__(version) + Asynchronous coroutine that deletes the KeyInstance - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Keys/{sid}.json'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KeyInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> KeyInstance: """ Fetch the KeyInstance + :returns: The fetched KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KeyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> KeyInstance: + """ + Asynchronous coroutine to fetch the KeyInstance + + + :returns: The fetched KeyInstance + """ + payload, _, _ = await self._fetch_async() 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"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KeyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation - def update(self, friendly_name=values.unset): + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._update(friendly_name=friendly_name) + return KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the KeyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> KeyInstance: + """ + Asynchronous coroutine to update the KeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated KeyInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) 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_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: """ - Deletes the KeyInstance + Asynchronous coroutine to update the KeyInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class KeyInstance(InstanceResource): - """ """ +class KeyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> KeyInstance: + """ + Build an instance of KeyInstance + + :param payload: Payload response from the API + """ - def __init__(self, version, payload, account_sid, sid=None): + return KeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class KeyList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - Initialize the 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'], + Asynchronously streams KeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams KeyInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams KeyInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KeyInstance]: + """ + Lists KeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KeyInstance]: """ - :returns: The unique string that identifies 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['sid'] - @property - def friendly_name(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Lists KeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['friendly_name'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def date_created(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + Asynchronously lists KeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_created'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> KeyPage: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :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_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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KeyPage(self._version, response, solution=self._solution) + + async def 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: """ - Fetch the KeyInstance + Asynchronously retrieve a single page of KeyInstance records from the API. + Request is executed immediately - :returns: The fetched KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyInstance + :param page_token: PageToken provided by the API + :param page_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._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 update(self, friendly_name=values.unset): + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KeyPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Update the KeyInstance + Retrieve a single page with response metadata - :param unicode friendly_name: A string to describe the resource - :returns: The updated KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyInstance + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with KeyPage, status code, and headers """ - return self._proxy.update(friendly_name=friendly_name, ) + data = values.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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = KeyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the KeyInstance + Asynchronously retrieve a single page with response metadata - :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: ApiResponse with KeyPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = KeyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> KeyPage: + """ + Retrieve a specific page of KeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KeyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return KeyPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> KeyPage: + """ + Asynchronously retrieve a specific page of KeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KeyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return KeyPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> KeyContext: + """ + Constructs a KeyContext + + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + return KeyContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> KeyContext: + """ + Constructs a KeyContext + + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + return KeyContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 58c5791b92..38182a2c9b 100644 --- a/twilio/rest/api/v2010/account/message/__init__.py +++ b/twilio/rest/api/v2010/account/message/__init__.py @@ -1,699 +1,1841 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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) + class RiskCheck(object): + ENABLE = "enable" + DISABLE = "disable" - def create(self, to, status_callback=values.unset, application_sid=values.unset, - max_price=values.unset, provide_feedback=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 ScheduleType(object): + FIXED = "fixed" + + class Status(object): + QUEUED = "queued" + SENDING = "sending" + SENT = "sent" + FAILED = "failed" + DELIVERED = "delivered" + UNDELIVERED = "undelivered" + RECEIVING = "receiving" + RECEIVED = "received" + ACCEPTED = "accepted" + SCHEDULED = "scheduled" + READ = "read" + PARTIALLY_DELIVERED = "partially_delivered" + CANCELED = "canceled" - :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 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 TrafficType(object): + FREE = "free" - :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, - '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 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'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, to=values.unset, from_=values.unset, - date_sent_before=values.unset, date_sent=values.unset, - date_sent_after=values.unset, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists MessageInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the MessageInstance - :param unicode to: Filter by messages 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 delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately + Deletes the MessageInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - 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.delete_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info - return MessagePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with success boolean, status code, and headers """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately + return await self._proxy.delete_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance - :returns: Page of MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessagePage + + :returns: The fetched MessageInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance - return MessagePage(self._version, response, self._solution) - def get(self, sid): + :returns: The fetched MessageInstance """ - Constructs a MessageContext + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return MessageContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.fetch_with_http_info() - def __call__(self, sid): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Constructs a MessageContext + Asynchronous coroutine to fetch the MessageInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return MessageContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.fetch_with_http_info_async() - def __repr__(self): + def update( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> "MessageInstance": """ - Provide a friendly representation + Update the MessageInstance - :returns: Machine friendly representation - :rtype: str + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: The updated MessageInstance """ - return '' + return self._proxy.update( + body=body, + status=status, + ) + async def update_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance -class MessagePage(Page): - """ """ + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: The updated MessageInstance + """ + return await self._proxy.update_async( + body=body, + status=status, + ) - def __init__(self, version, response, solution): + def update_with_http_info( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> ApiResponse: """ - Initialize the MessagePage + Update the MessageInstance with HTTP info - :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 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.MessagePage - :rtype: twilio.rest.api.v2010.account.message.MessagePage + :returns: ApiResponse with instance, status code, and headers """ - super(MessagePage, self).__init__(version, response) + return self._proxy.update_with_http_info( + body=body, + status=status, + ) - # Path Solution - self._solution = solution + async def update_with_http_info_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info - def get_instance(self, payload): + :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: ApiResponse with instance, status code, and headers """ - Build an instance of MessageInstance + return await self._proxy.update_with_http_info_async( + body=body, + status=status, + ) - :param dict payload: Payload response from the API + @property + def feedback(self) -> FeedbackList: + """ + Access the feedback + """ + return self._proxy.feedback - :returns: twilio.rest.api.v2010.account.message.MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessageInstance + @property + def media(self) -> MediaList: + """ + Access the media """ - return MessageInstance(self._version, payload, account_sid=self._solution['account_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 MessageContext(InstanceContext): - """ """ - def __init__(self, version, account_sid, sid): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the MessageContext - :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 + :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(MessageContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Messages/{sid}.json'.format(**self._solution) + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Messages/{sid}.json".format( + **self._solution + ) - # Dependents - self._media = None - self._feedback = None + self._feedback: Optional[FeedbackList] = None + self._media: Optional[MediaList] = None - def delete(self): + def _delete(self) -> tuple: """ - Deletes the MessageInstance + Internal helper for delete operation - :returns: True if delete succeeds, False otherwise - :rtype: bool + Returns: + tuple: (success_boolean, status_code, headers) """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def fetch(self): + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - Fetch the MessageInstance + Deletes the MessageInstance - :returns: The fetched MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessageInstance + + :returns: True if delete succeeds, False otherwise """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessageInstance and return response metadata - return MessageInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - def update(self, body): + :returns: ApiResponse with success boolean, status code, and headers """ - Update the MessageInstance + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :param unicode body: The text of the message you want to send + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation - :returns: The updated MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessageInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - data = values.of({'Body': body, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers = values.of({}) - return MessageInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - @property - def media(self): + async def delete_async(self) -> bool: """ - Access the media + Asynchronous coroutine that deletes the MessageInstance + - :returns: twilio.rest.api.v2010.account.message.media.MediaList - :rtype: twilio.rest.api.v2010.account.message.media.MediaList + :returns: True if delete succeeds, False otherwise """ - if self._media is None: - self._media = MediaList( - self._version, - account_sid=self._solution['account_sid'], - message_sid=self._solution['sid'], - ) - return self._media + success, _, _ = await self._delete_async() + return success - @property - def feedback(self): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Access the feedback + Asynchronous coroutine that deletes the MessageInstance and return response metadata - :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackList - :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackList + + :returns: ApiResponse with success boolean, status code, and headers """ - if self._feedback is None: - self._feedback = FeedbackList( - self._version, - account_sid=self._solution['account_sid'], - message_sid=self._solution['sid'], - ) - return self._feedback + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __repr__(self): + def _fetch(self) -> tuple: """ - Provide a friendly representation + Internal helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) -class MessageInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - 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" + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - class Direction(object): - INBOUND = "inbound" - OUTBOUND_API = "outbound-api" - OUTBOUND_CALL = "outbound-call" - OUTBOUND_REPLY = "outbound-reply" + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance - class ContentRetention(object): - RETAIN = "retain" - class AddressRetention(object): - RETAIN = "retain" + :returns: The fetched MessageInstance + """ + payload, _, _ = self._fetch() + return MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - class TrafficType(object): - FREE = "free" + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance and return response metadata - def __init__(self, version, payload, account_sid, sid=None): - """ - Initialize the MessageInstance - - :returns: twilio.rest.api.v2010.account.message.MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessageInstance - """ - super(MessageInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'api_version': payload.get('api_version'), - 'body': payload.get('body'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'date_sent': deserialize.rfc2822_datetime(payload.get('date_sent')), - 'direction': payload.get('direction'), - 'error_code': deserialize.integer(payload.get('error_code')), - 'error_message': payload.get('error_message'), - 'from_': payload.get('from'), - 'messaging_service_sid': payload.get('messaging_service_sid'), - 'num_media': payload.get('num_media'), - 'num_segments': payload.get('num_segments'), - 'price': payload.get('price'), - 'price_unit': payload.get('price_unit'), - 'sid': payload.get('sid'), - 'status': payload.get('status'), - 'subresource_uris': payload.get('subresource_uris'), - 'to': payload.get('to'), - 'uri': payload.get('uri'), - } - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def _proxy(self): + async def _fetch_async(self) -> tuple: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Internal async helper for fetch operation - :returns: MessageContext for this MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessageContext + Returns: + tuple: (payload, status_code, headers) """ - if self._context is None: - self._context = MessageContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context - @property - def account_sid(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> MessageInstance: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance """ - return self._properties['account_sid'] + payload, _, _ = await self._fetch_async() + return MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - @property - def api_version(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: The API version used to process the message - :rtype: unicode + Asynchronous coroutine to fetch the MessageInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['api_version'] + payload, status_code, headers = await self._fetch_async() + instance = MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def body(self): + def _update( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> tuple: """ - :returns: The message text - :rtype: unicode + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['body'] - @property - def date_created(self): + data = values.of( + { + "Body": body, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> MessageInstance: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + Update the MessageInstance + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: The updated MessageInstance """ - return self._properties['date_created'] + payload, _, _ = self._update(body=body, status=status) + return MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - @property - def date_updated(self): + def update_with_http_info( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> ApiResponse: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + Update the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['date_updated'] + payload, status_code, headers = self._update(body=body, status=status) + instance = MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def date_sent(self): + async def _update_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> tuple: """ - :returns: The RFC 2822 date and time in GMT when the message was sent - :rtype: datetime + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['date_sent'] - @property - def direction(self): + data = values.of( + { + "Body": body, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> MessageInstance: """ - :returns: The direction of the message - :rtype: MessageInstance.Direction + Asynchronous coroutine to update the MessageInstance + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: The updated MessageInstance """ - return self._properties['direction'] + payload, _, _ = await self._update_async(body=body, status=status) + return MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - @property - def error_code(self): + async def update_with_http_info_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> ApiResponse: """ - :returns: The error code associated with the message - :rtype: unicode + Asynchronous coroutine to update the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['error_code'] + payload, status_code, headers = await self._update_async( + body=body, status=status + ) + instance = MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def error_message(self): + def feedback(self) -> FeedbackList: """ - :returns: The description of the error_code - :rtype: unicode + Access the feedback """ - return self._properties['error_message'] + if self._feedback is None: + self._feedback = FeedbackList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._feedback @property - def from_(self): + def media(self) -> MediaList: """ - :returns: The phone number that initiated the message - :rtype: unicode + Access the media """ - return self._properties['from_'] + if self._media is None: + self._media = MediaList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._media - @property - def messaging_service_sid(self): + def __repr__(self) -> str: """ - :returns: The SID of the Messaging Service used with the message. - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['messaging_service_sid'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def num_media(self): + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: """ - :returns: The number of media files associated with the message - :rtype: unicode + Build an instance of MessageInstance + + :param payload: Payload response from the API """ - return self._properties['num_media'] - @property - def num_segments(self): + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: """ - :returns: The number of messages used to deliver the message body - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['num_segments'] + return "" - @property - def price(self): + +class MessageList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - :returns: The amount billed for the message - :rtype: unicode + Initialize the MessageList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Message resources. + """ - return self._properties['price'] + super().__init__(version) - @property - def price_unit(self): + # 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, + fallback_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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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_, + "FallbackFrom": fallback_from, + "MessagingServiceSid": messaging_service_sid, + "Body": body, + "MediaUrl": serialize.map(media_url, lambda e: e), + "ContentSid": content_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + fallback_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: """ - :returns: The currency in which price is measured - :rtype: unicode + 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 fallback_from: A fallback SMS sender to use when the recipient cannot be reached over RCS. This parameter may only be used when also providing a [Messaging Service](https://twilio.com/docs/messaging/services) containing an RCS sender. The fallback SMS sender must be either a Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), or [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), hosted within Twilio and belong to the Account creating the Message. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. + :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). + :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. + :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + + :returns: The created MessageInstance """ - return self._properties['price_unit'] + payload, _, _ = self._create( + to=to, + status_callback=status_callback, + application_sid=application_sid, + max_price=max_price, + provide_feedback=provide_feedback, + attempt=attempt, + validity_period=validity_period, + force_delivery=force_delivery, + content_retention=content_retention, + address_retention=address_retention, + smart_encoded=smart_encoded, + persistent_action=persistent_action, + traffic_type=traffic_type, + shorten_urls=shorten_urls, + schedule_type=schedule_type, + send_at=send_at, + send_as_mms=send_as_mms, + content_variables=content_variables, + risk_check=risk_check, + from_=from_, + fallback_from=fallback_from, + messaging_service_sid=messaging_service_sid, + body=body, + media_url=media_url, + content_sid=content_sid, + ) + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def sid(self): + def create_with_http_info( + 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, + fallback_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, + ) -> ApiResponse: + """ + Create the MessageInstance and return response metadata + + :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 fallback_from: A fallback SMS sender to use when the recipient cannot be reached over RCS. This parameter may only be used when also providing a [Messaging Service](https://twilio.com/docs/messaging/services) containing an RCS sender. The fallback SMS sender must be either a Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), or [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), hosted within Twilio and belong to the Account creating the Message. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. + :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). + :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. + :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + to=to, + status_callback=status_callback, + application_sid=application_sid, + max_price=max_price, + provide_feedback=provide_feedback, + attempt=attempt, + validity_period=validity_period, + force_delivery=force_delivery, + content_retention=content_retention, + address_retention=address_retention, + smart_encoded=smart_encoded, + persistent_action=persistent_action, + traffic_type=traffic_type, + shorten_urls=shorten_urls, + schedule_type=schedule_type, + send_at=send_at, + send_as_mms=send_as_mms, + content_variables=content_variables, + risk_check=risk_check, + from_=from_, + fallback_from=fallback_from, + messaging_service_sid=messaging_service_sid, + body=body, + media_url=media_url, + content_sid=content_sid, + ) + instance = MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + fallback_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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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_, + "FallbackFrom": fallback_from, + "MessagingServiceSid": messaging_service_sid, + "Body": body, + "MediaUrl": serialize.map(media_url, lambda e: e), + "ContentSid": content_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + fallback_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 fallback_from: A fallback SMS sender to use when the recipient cannot be reached over RCS. This parameter may only be used when also providing a [Messaging Service](https://twilio.com/docs/messaging/services) containing an RCS sender. The fallback SMS sender must be either a Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), or [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), hosted within Twilio and belong to the Account creating the Message. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. + :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). + :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. + :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + + :returns: The created MessageInstance """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = await self._create_async( + to=to, + status_callback=status_callback, + application_sid=application_sid, + max_price=max_price, + provide_feedback=provide_feedback, + attempt=attempt, + validity_period=validity_period, + force_delivery=force_delivery, + content_retention=content_retention, + address_retention=address_retention, + smart_encoded=smart_encoded, + persistent_action=persistent_action, + traffic_type=traffic_type, + shorten_urls=shorten_urls, + schedule_type=schedule_type, + send_at=send_at, + send_as_mms=send_as_mms, + content_variables=content_variables, + risk_check=risk_check, + from_=from_, + fallback_from=fallback_from, + messaging_service_sid=messaging_service_sid, + body=body, + media_url=media_url, + content_sid=content_sid, + ) + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_with_http_info_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, + fallback_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, + ) -> ApiResponse: + """ + Asynchronously create the MessageInstance and return response metadata + + :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 fallback_from: A fallback SMS sender to use when the recipient cannot be reached over RCS. This parameter may only be used when also providing a [Messaging Service](https://twilio.com/docs/messaging/services) containing an RCS sender. The fallback SMS sender must be either a Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), or [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), hosted within Twilio and belong to the Account creating the Message. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. + :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). + :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. + :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + to=to, + status_callback=status_callback, + application_sid=application_sid, + max_price=max_price, + provide_feedback=provide_feedback, + attempt=attempt, + validity_period=validity_period, + force_delivery=force_delivery, + content_retention=content_retention, + address_retention=address_retention, + smart_encoded=smart_encoded, + persistent_action=persistent_action, + traffic_type=traffic_type, + shorten_urls=shorten_urls, + schedule_type=schedule_type, + send_at=send_at, + send_as_mms=send_as_mms, + content_variables=content_variables, + risk_check=risk_check, + from_=from_, + fallback_from=fallback_from, + messaging_service_sid=messaging_service_sid, + body=body, + media_url=media_url, + content_sid=content_sid, + ) + instance = MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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['sid'] + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - @property - def status(self): + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+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 """ - :returns: The status of the message - :rtype: MessageInstance.Status + limits = self._version.read_limits(limit, page_size) + page = self.page( + to=to, + from_=from_, + date_sent=date_sent, + date_sent_before=date_sent_before, + date_sent_after=date_sent_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: """ - return self._properties['status'] + 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 subresource_uris(self): + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+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 """ - :returns: A list of related resources identified by their relative URIs - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + to=to, + from_=from_, + date_sent=date_sent, + date_sent_before=date_sent_before, + date_sent_after=date_sent_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: """ - return self._properties['subresource_uris'] + Streams MessageInstance and returns headers from first page - @property - def to(self): + + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The phone number that received the message - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams MessageInstance and returns headers from first page + + + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['to'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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 uri(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :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 parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+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 parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists MessageInstance and returns headers from first page + + + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists MessageInstance and returns headers from first page + + + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: """ - return self._properties['uri'] + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. + :param date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - def delete(self): + :returns: Page of MessageInstance """ - Deletes the MessageInstance + data = values.of( + { + "To": to, + "From": from_, + "DateSent": serialize.iso8601_datetime(date_sent), + "DateSent<": serialize.iso8601_datetime(date_sent_before), + "DateSent>": serialize.iso8601_datetime(date_sent_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, solution=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 parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+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: ApiResponse with MessagePage, status code, and headers + """ + 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"}) - def fetch(self): + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+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: ApiResponse with MessagePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..5922ead4e2 100644 --- a/twilio/rest/api/v2010/account/message/feedback.py +++ b/twilio/rest/api/v2010/account/message/feedback.py @@ -1,197 +1,229 @@ -# 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, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource -from twilio.base.page import Page +from twilio.base.version import Version -class FeedbackList(ListResource): - """ """ - - def __init__(self, version, account_sid, message_sid): - """ - Initialize the FeedbackList +class FeedbackInstance(InstanceResource): - :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 + class Outcome(object): + CONFIRMED = "confirmed" + UNCONFIRMED = "unconfirmed" - :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackList - :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackList - """ - super(FeedbackList, self).__init__(version) + """ + :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") - # 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) + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + } - def create(self, outcome=values.unset): + def __repr__(self) -> str: """ - Create the FeedbackInstance - - :param FeedbackInstance.Outcome outcome: Whether the feedback has arrived + Provide a friendly representation - :returns: The created FeedbackInstance - :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance + :returns: Machine friendly representation """ - data = values.of({'Outcome': outcome, }) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return FeedbackInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - message_sid=self._solution['message_sid'], - ) +class FeedbackList(ListResource): - def __repr__(self): + def __init__(self, version: Version, account_sid: str, message_sid: str): """ - Provide a friendly representation + Initialize the FeedbackList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Message resource for which to create MessageFeedback. + :param message_sid: The SID of the Message resource for which to create MessageFeedback. - :returns: Machine friendly representation - :rtype: str """ - return '' + super().__init__(version) + # Path Solution + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + } + self._uri = ( + "/Accounts/{account_sid}/Messages/{message_sid}/Feedback.json".format( + **self._solution + ) + ) -class FeedbackPage(Page): - """ """ + def _create( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> tuple: + """ + Internal helper for create operation - def __init__(self, version, response, solution): + Returns: + tuple: (payload, status_code, headers) """ - Initialize the FeedbackPage - :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 + data = values.of( + { + "Outcome": outcome, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackPage - :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackPage - """ - super(FeedbackPage, self).__init__(version, response) + headers["Content-Type"] = "application/x-www-form-urlencoded" - # Path Solution - self._solution = solution + headers["Accept"] = "application/json" - def get_instance(self, payload): + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> FeedbackInstance: """ - Build an instance of FeedbackInstance + Create the FeedbackInstance - :param dict payload: Payload response from the API + :param outcome: - :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance - :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance + :returns: The created FeedbackInstance """ + payload, _, _ = self._create(outcome=outcome) return FeedbackInstance( 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"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + def create_with_http_info( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> ApiResponse: """ - return '' + Create the FeedbackInstance and return response metadata + :param outcome: -class FeedbackInstance(InstanceResource): - """ """ - - class Outcome(object): - CONFIRMED = "confirmed" - UNCONFIRMED = "unconfirmed" + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(outcome=outcome) + instance = FeedbackInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __init__(self, version, payload, account_sid, message_sid): + async def _create_async( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> tuple: """ - Initialize the FeedbackInstance + Internal async helper for create operation - :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance - :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance + Returns: + tuple: (payload, status_code, headers) """ - 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'), - } + data = values.of( + { + "Outcome": outcome, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'message_sid': message_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 message_sid(self): - """ - :returns: The SID of the Message resource for which the feedback was provided - :rtype: unicode - """ - return self._properties['message_sid'] + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def outcome(self): - """ - :returns: Whether the feedback has arrived - :rtype: FeedbackInstance.Outcome + async def create_async( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> FeedbackInstance: """ - return self._properties['outcome'] + Asynchronously create the FeedbackInstance - @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 outcome: - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + :returns: The created FeedbackInstance """ - return self._properties['date_updated'] + payload, _, _ = await self._create_async(outcome=outcome) + return FeedbackInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + ) - @property - def uri(self): + async def create_with_http_info_async( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> ApiResponse: """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + Asynchronously create the FeedbackInstance and return response metadata + + :param outcome: + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['uri'] + payload, status_code, headers = await self._create_async(outcome=outcome) + instance = FeedbackInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 64a1428585..d15bc20f18 100644 --- a/twilio/rest/api/v2010/account/message/media.py +++ b/twilio/rest/api/v2010/account/message/media.py @@ -1,422 +1,925 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +class MediaInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with this Media resource. + :ivar content_type: The default [MIME type](https://en.wikipedia.org/wiki/Internet_media_type) of the media, for example `image/jpeg`, `image/png`, or `image/gif`. + :ivar date_created: The date and time in GMT when this Media resource was created, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when this Media resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar parent_sid: The SID of the Message resource that is associated with this Media resource. + :ivar sid: The unique string that identifies this Media resource. + :ivar uri: The URI of this Media resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + message_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.content_type: Optional[str] = payload.get("content_type") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.parent_sid: Optional[str] = payload.get("parent_sid") + self.sid: Optional[str] = payload.get("sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + "sid": sid or self.sid, + } + + self._context: Optional[MediaContext] = None - def __init__(self, version, account_sid, message_sid): + @property + def _proxy(self) -> "MediaContext": """ - Initialize the MediaList + 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 this resource - :param message_sid: The unique string that identifies the resource + :returns: MediaContext for this MediaInstance + """ + if self._context is None: + self._context = MediaContext( + self._version, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.api.v2010.account.message.media.MediaList - :rtype: twilio.rest.api.v2010.account.message.media.MediaList + def delete(self) -> bool: """ - super(MediaList, self).__init__(version) + Deletes the MediaInstance - # Path Solution - self._solution = {'account_sid': account_sid, 'message_sid': message_sid, } - self._uri = '/Accounts/{account_sid}/Messages/{message_sid}/Media.json'.format(**self._solution) - def stream(self, date_created_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 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. + return self._proxy.delete() - :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) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MediaInstance - :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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page( - date_created_before=date_created_before, - date_created=date_created, - date_created_after=date_created_after, - page_size=limits['page_size'], - ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MediaInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists MediaInstance 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.delete_with_http_info() - :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) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MediaInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.message.media.MediaInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - 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_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MediaInstance with HTTP info - :returns: Page of MediaInstance - :rtype: twilio.rest.api.v2010.account.message.media.MediaPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MediaInstance with HTTP info - return MediaPage(self._version, response, self._solution) - def get(self, sid): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a MediaContext + return await self._proxy.fetch_with_http_info_async() - :param sid: The unique string that identifies this resource + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.message.media.MediaContext - :rtype: twilio.rest.api.v2010.account.message.media.MediaContext + :returns: Machine friendly representation """ - return MediaContext( - self._version, - account_sid=self._solution['account_sid'], - message_sid=self._solution['message_sid'], - sid=sid, + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MediaContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, message_sid: str, sid: str): + """ + Initialize the MediaContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Media resource. + :param message_sid: The SID of the Message resource that is associated with the Media resource. + :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/Messages/{message_sid}/Media/{sid}.json".format( + **self._solution + ) ) - def __call__(self, sid): + def _delete(self) -> tuple: """ - Constructs a MediaContext + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param sid: The unique string that identifies this resource + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.api.v2010.account.message.media.MediaContext - :rtype: twilio.rest.api.v2010.account.message.media.MediaContext + def delete(self) -> bool: """ - return MediaContext( - self._version, - account_sid=self._solution['account_sid'], - message_sid=self._solution['message_sid'], - sid=sid, + Deletes the MediaInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MediaInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + 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 '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MediaInstance and return response metadata -class MediaPage(Page): - """ """ - def __init__(self, version, response, solution): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the MediaPage + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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 message_sid: The unique string that identifies the resource + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.api.v2010.account.message.media.MediaPage - :rtype: twilio.rest.api.v2010.account.message.media.MediaPage + Returns: + tuple: (payload, status_code, headers) """ - super(MediaPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) + + headers["Accept"] = "application/json" - def get_instance(self, payload): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MediaInstance: """ - Build an instance of MediaInstance + Fetch the MediaInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.message.media.MediaInstance - :rtype: twilio.rest.api.v2010.account.message.media.MediaInstance + :returns: The fetched MediaInstance """ + payload, _, _ = self._fetch() 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Fetch the MediaInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - return '' + payload, status_code, headers = self._fetch() + instance = MediaInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation -class MediaContext(InstanceContext): - """ """ + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, account_sid, message_sid, sid): + async def fetch_async(self) -> MediaInstance: """ - Initialize the MediaContext + Asynchronous coroutine to fetch the MediaInstance + - :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 + :returns: The fetched MediaInstance + """ + payload, _, _ = await self._fetch_async() + 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 + async def fetch_with_http_info_async(self) -> ApiResponse: """ - super(MediaContext, self).__init__(version) + Asynchronous coroutine to fetch the MediaInstance and return response metadata - # Path Solution - self._solution = {'account_sid': account_sid, 'message_sid': message_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Messages/{message_sid}/Media/{sid}.json'.format(**self._solution) - def delete(self): + :returns: ApiResponse with instance, status code, and headers """ - Deletes the MediaInstance + payload, status_code, headers = await self._fetch_async() + instance = MediaInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def __repr__(self) -> str: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Provide a friendly representation - def fetch(self): + :returns: Machine friendly representation """ - Fetch the MediaInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: The fetched MediaInstance - :rtype: twilio.rest.api.v2010.account.message.media.MediaInstance + +class MediaPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MediaInstance: + """ + Build an instance of MediaInstance + + :param payload: Payload response from the API """ - payload = self._version.fetch(method='GET', uri=self._uri, ) 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 + :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 """ - 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 + 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 account_sid(self): + 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]: """ - :returns: The SID of the Account that created this resource - :rtype: unicode + Asynchronously streams MediaInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) - @property - def content_type(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: """ - :returns: The default mime-type of the media - :rtype: unicode + Streams MediaInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['content_type'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) - @property - def date_created(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - :returns: The RFC 2822 date and time in GMT that this resource was created - :rtype: datetime + Asynchronously streams MediaInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - :returns: The RFC 2822 date and time in GMT that this resource was last updated - :rtype: datetime + Lists MediaInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MediaInstance]: """ - return self._properties['date_updated'] + 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. - @property - def parent_sid(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 [ + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists MediaInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers """ - :returns: The SID of the resource that created the media - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists MediaInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['parent_sid'] + Retrieve a single page of MediaInstance records from the API. + Request is executed immediately - @property - def sid(self): + :param date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MediaInstance """ - :returns: The unique string that identifies this resource - :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, solution=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['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 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 MediaPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with MediaPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MediaPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with MediaPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MediaPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> MediaPage: """ - :returns: The URI of this resource, relative to `https://api.twilio.com` - :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['uri'] + response = self._version.domain.twilio.request("GET", target_url) + return MediaPage(self._version, response, solution=self._solution) - def delete(self): + async def get_page_async(self, target_url: str) -> MediaPage: """ - Deletes the MediaInstance + Asynchronously retrieve a specific page of MediaInstance 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 MediaInstance """ - return self._proxy.delete() + response = await self._version.domain.twilio.request_async("GET", target_url) + return MediaPage(self._version, response, solution=self._solution) - def fetch(self): + def get(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 __call__(self, sid: str) -> MediaContext: + """ + Constructs a MediaContext + + :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch. + """ + return MediaContext( + self._version, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..525891af56 100644 --- a/twilio/rest/api/v2010/account/new_key.py +++ b/twilio/rest/api/v2010/account/new_key.py @@ -1,172 +1,197 @@ -# 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, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + 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 NewKeyList(ListResource): - """ """ +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 __init__(self, version, account_sid): + def __repr__(self) -> str: """ - Initialize the NewKeyList - - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.new_key.NewKeyList - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyList + :returns: Machine friendly representation """ - super(NewKeyList, self).__init__(version) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # 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): +class NewKeyList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - Create the NewKeyInstance + Initialize the NewKeyList - :param unicode friendly_name: A string to describe 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 be responsible for the new Key resource. - :returns: The created NewKeyInstance - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyInstance """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + super().__init__(version) - return NewKeyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Keys.json".format(**self._solution) - def __repr__(self): + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: """ - Provide a friendly representation + Internal helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class NewKeyPage(Page): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, response, solution): - """ - Initialize the NewKeyPage + headers["Accept"] = "application/json" - :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. + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.api.v2010.account.new_key.NewKeyPage - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyPage + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> NewKeyInstance: """ - super(NewKeyPage, self).__init__(version, response) + Create the NewKeyInstance - # Path Solution - self._solution = solution + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - def get_instance(self, payload): + :returns: The created NewKeyInstance """ - Build an instance of NewKeyInstance + payload, _, _ = self._create(friendly_name=friendly_name) + return NewKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.new_key.NewKeyInstance - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyInstance + def create_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: """ - return NewKeyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Create the NewKeyInstance and return response metadata - def __repr__(self): - """ - Provide a friendly representation + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: Machine friendly representation - :rtype: str + :returns: ApiResponse with instance, status code, and headers """ - return '' - + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = NewKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) -class NewKeyInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid): + async def _create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: """ - Initialize the NewKeyInstance + Internal async helper for create operation - :returns: twilio.rest.api.v2010.account.new_key.NewKeyInstance - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyInstance + Returns: + tuple: (payload, status_code, headers) """ - 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'), - } + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + 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 sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['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'] + return await self._version.create_with_response_info_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 + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> NewKeyInstance: """ - return self._properties['date_created'] + Asynchronously create the NewKeyInstance - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewKeyInstance """ - return self._properties['date_updated'] + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return NewKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def secret(self): + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: """ - :returns: The secret your application uses to sign Access Tokens and to authenticate to the REST API. - :rtype: unicode + Asynchronously create the NewKeyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['secret'] + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = NewKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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..ebbb680958 100644 --- a/twilio/rest/api/v2010/account/new_signing_key.py +++ b/twilio/rest/api/v2010/account/new_signing_key.py @@ -1,172 +1,197 @@ -# 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, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + 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 NewSigningKeyList(ListResource): - """ """ +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 __init__(self, version, account_sid): + def __repr__(self) -> str: """ - Initialize the NewSigningKeyList - - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyList - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyList + :returns: Machine friendly representation """ - super(NewSigningKeyList, self).__init__(version) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # 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): +class NewSigningKeyList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - Create the NewSigningKeyInstance + Initialize the NewSigningKeyList - :param unicode friendly_name: A string to describe 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 be responsible for the new Key resource. - :returns: The created NewSigningKeyInstance - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyInstance """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + super().__init__(version) - return NewSigningKeyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SigningKeys.json".format(**self._solution) - def __repr__(self): + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: """ - Provide a friendly representation + Internal helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class NewSigningKeyPage(Page): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, response, solution): - """ - Initialize the NewSigningKeyPage + headers["Accept"] = "application/json" - :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. + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyPage - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyPage + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> NewSigningKeyInstance: """ - super(NewSigningKeyPage, self).__init__(version, response) + Create the NewSigningKeyInstance - # Path Solution - self._solution = solution + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - def get_instance(self, payload): + :returns: The created NewSigningKeyInstance """ - Build an instance of NewSigningKeyInstance + payload, _, _ = self._create(friendly_name=friendly_name) + return NewSigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyInstance - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyInstance + def create_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: """ - return NewSigningKeyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Create the NewSigningKeyInstance and return response metadata - def __repr__(self): - """ - Provide a friendly representation + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: Machine friendly representation - :rtype: str + :returns: ApiResponse with instance, status code, and headers """ - return '' - + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = NewSigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) -class NewSigningKeyInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid): + async def _create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: """ - Initialize the NewSigningKeyInstance + Internal async helper for create operation - :returns: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyInstance - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyInstance + Returns: + tuple: (payload, status_code, headers) """ - 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'), - } + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + 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 sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['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'] + return await self._version.create_with_response_info_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 + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> NewSigningKeyInstance: """ - return self._properties['date_created'] + Asynchronously create the NewSigningKeyInstance - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewSigningKeyInstance """ - return self._properties['date_updated'] + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return NewSigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def secret(self): + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: """ - :returns: The secret your application uses to sign Access Tokens and to authenticate to the REST API. - :rtype: unicode + Asynchronously create the NewSigningKeyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['secret'] + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = NewSigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 5713084502..9afbd26354 100644 --- a/twilio/rest/api/v2010/account/notification.py +++ b/twilio/rest/api/v2010/account/notification.py @@ -1,479 +1,857 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ - 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 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, + } - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource + self._context: Optional[NotificationContext] = None - :returns: twilio.rest.api.v2010.account.notification.NotificationList - :rtype: twilio.rest.api.v2010.account.notification.NotificationList + @property + def _proxy(self) -> "NotificationContext": """ - super(NotificationList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Notifications.json'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def stream(self, log=values.unset, message_date_before=values.unset, - message_date=values.unset, message_date_after=values.unset, - limit=None, page_size=None): + :returns: NotificationContext for this NotificationInstance """ - Streams NotificationInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param unicode log: 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) + if self._context is None: + self._context = NotificationContext( + 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.notification.NotificationInstance] + def fetch(self) -> "NotificationInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the NotificationInstance - page = self.page( - log=log, - message_date_before=message_date_before, - message_date=message_date, - message_date_after=message_date_after, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched NotificationInstance + """ + return self._proxy.fetch() - def list(self, log=values.unset, message_date_before=values.unset, - message_date=values.unset, message_date_after=values.unset, limit=None, - page_size=None): + async def fetch_async(self) -> "NotificationInstance": """ - Lists NotificationInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine to fetch the NotificationInstance - :param unicode log: Filter by log level - :param date message_date_before: Filter by date - :param date message_date: Filter by date - :param date message_date_after: Filter by date - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.notification.NotificationInstance] + :returns: The fetched NotificationInstance """ - return list(self.stream( - log=log, - message_date_before=message_date_before, - message_date=message_date, - message_date_after=message_date_after, - limit=limit, - page_size=page_size, - )) + return await self._proxy.fetch_async() - def page(self, log=values.unset, message_date_before=values.unset, - message_date=values.unset, message_date_after=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of NotificationInstance records from the API. - Request is executed immediately + Fetch the NotificationInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - 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, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return NotificationPage(self._version, response, self._solution) - - def get_page(self, target_url): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Retrieve a specific page of NotificationInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the NotificationInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.fetch_with_http_info_async() - return NotificationPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a NotificationContext + 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 NotificationContext(InstanceContext): - :returns: twilio.rest.api.v2010.account.notification.NotificationContext - :rtype: twilio.rest.api.v2010.account.notification.NotificationContext + def __init__(self, version: Version, account_sid: str, sid: str): """ - return NotificationContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + Initialize the NotificationContext - 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 Notification resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Notification resource to fetch. """ - Constructs a NotificationContext + 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}/Notifications/{sid}.json".format( + **self._solution + ) - :returns: twilio.rest.api.v2010.account.notification.NotificationContext - :rtype: twilio.rest.api.v2010.account.notification.NotificationContext + def _fetch(self) -> tuple: """ - return NotificationContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + Internal helper for fetch operation - def __repr__(self): + Returns: + tuple: (payload, status_code, headers) """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers = values.of({}) + headers["Accept"] = "application/json" -class NotificationPage(Page): - """ """ + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> NotificationInstance: """ - Initialize the NotificationPage + Fetch the NotificationInstance - :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.notification.NotificationPage - :rtype: twilio.rest.api.v2010.account.notification.NotificationPage + :returns: The fetched NotificationInstance """ - super(NotificationPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = self._fetch() + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - def get_instance(self, payload): + def fetch_with_http_info(self) -> ApiResponse: """ - Build an instance of NotificationInstance + Fetch the NotificationInstance and return response metadata - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.notification.NotificationInstance - :rtype: twilio.rest.api.v2010.account.notification.NotificationInstance + :returns: ApiResponse with instance, status code, and headers """ - return NotificationInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + payload, status_code, headers = self._fetch() + instance = NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' - -class NotificationContext(InstanceContext): - """ """ + headers = values.of({}) - def __init__(self, version, account_sid, sid): - """ - Initialize the NotificationContext + headers["Accept"] = "application/json" - :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 await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: twilio.rest.api.v2010.account.notification.NotificationContext - :rtype: twilio.rest.api.v2010.account.notification.NotificationContext + async def fetch_async(self) -> NotificationInstance: """ - super(NotificationContext, self).__init__(version) + Asynchronous coroutine to fetch the NotificationInstance - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Notifications/{sid}.json'.format(**self._solution) - def fetch(self): + :returns: The fetched NotificationInstance """ - Fetch the NotificationInstance + payload, _, _ = await self._fetch_async() + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - :returns: The fetched NotificationInstance - :rtype: twilio.rest.api.v2010.account.notification.NotificationInstance + async def fetch_with_http_info_async(self) -> ApiResponse: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronous coroutine to fetch the NotificationInstance and return response metadata - return NotificationInstance( + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = NotificationInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 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'), - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } +class NotificationPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> NotificationInstance: """ - 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 NotificationInstance - :returns: NotificationContext for this NotificationInstance - :rtype: twilio.rest.api.v2010.account.notification.NotificationContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = NotificationContext( - self._version, - account_sid=self._solution['account_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'] + return NotificationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def api_version(self): - """ - :returns: The API version used to generate the notification - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def call_sid(self): - """ - :returns: The SID of the Call the resource is associated with - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['call_sid'] + 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 NotificationList(ListResource): - @property - def error_code(self): + def __init__(self, version: Version, account_sid: str): """ - :returns: A unique error code corresponding to the notification - :rtype: unicode - """ - return self._properties['error_code'] + Initialize the NotificationList - @property - def log(self): - """ - :returns: An integer log level - :rtype: unicode - """ - return self._properties['log'] + :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. - @property - def message_date(self): - """ - :returns: The date the notification was generated - :rtype: datetime """ - return self._properties['message_date'] + super().__init__(version) - @property - def message_text(self): + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Notifications.json".format( + **self._solution + ) + + def stream( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NotificationInstance]: """ - :returns: The text of the notification - :rtype: unicode + Streams NotificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['message_text'] + 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"], + ) - @property - def more_info(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NotificationInstance]: """ - :returns: A URL for more information about the error code - :rtype: unicode + Asynchronously streams NotificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['more_info'] + 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"], + ) - @property - def request_method(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: """ - :returns: HTTP method used with the request url - :rtype: unicode + Streams NotificationInstance and returns headers from first page + + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['request_method'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) - @property - def request_url(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - :returns: URL of the resource that generated the notification - :rtype: unicode + Asynchronously streams NotificationInstance and returns headers from first page + + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['request_url'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) - @property - def request_variables(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - :returns: Twilio-generated HTTP variables sent to the server - :rtype: unicode + Lists NotificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NotificationInstance]: + """ + Asynchronously lists NotificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists NotificationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists NotificationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['request_variables'] + Retrieve a single page of NotificationInstance records from the API. + Request is executed immediately - @property - def response_body(self): + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NotificationInstance """ - :returns: The HTTP body returned by your server - :rtype: unicode + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NotificationPage(self._version, response, solution=self._solution) + + async def page_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NotificationPage: + """ + Asynchronously retrieve a single page of NotificationInstance records from the API. + Request is executed immediately + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NotificationInstance """ - return self._properties['response_body'] + 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 response_headers(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 NotificationPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NotificationPage, status code, and headers + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = NotificationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NotificationPage, status code, and headers + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = NotificationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> NotificationPage: """ - :returns: The HTTP headers returned by your server - :rtype: unicode + 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['response_headers'] + response = self._version.domain.twilio.request("GET", target_url) + return NotificationPage(self._version, response, solution=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, solution=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 0107e10a31..16f29c6f7d 100644 --- a/twilio/rest/api/v2010/account/outgoing_caller_id.py +++ b/twilio/rest/api/v2010/account/outgoing_caller_id.py @@ -1,422 +1,1047 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 + 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 + :returns: OutgoingCallerIdContext for this OutgoingCallerIdInstance + """ + if self._context is None: + self._context = OutgoingCallerIdContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList + def delete(self) -> bool: """ - super(OutgoingCallerIdList, self).__init__(version) + Deletes the OutgoingCallerIdInstance - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/OutgoingCallerIds.json'.format(**self._solution) - def stream(self, phone_number=values.unset, friendly_name=values.unset, - limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + 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. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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) + return await self._proxy.delete_async() - page = self.page( - phone_number=phone_number, - friendly_name=friendly_name, - page_size=limits['page_size'], - ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OutgoingCallerIdInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, phone_number=values.unset, friendly_name=values.unset, - limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists OutgoingCallerIdInstance 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.delete_with_http_info() - :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) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OutgoingCallerIdInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream( - phone_number=phone_number, - friendly_name=friendly_name, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_with_http_info_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 + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OutgoingCallerIdInstance": """ - data = values.of({ - 'PhoneNumber': phone_number, - 'FriendlyName': friendly_name, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Asynchronous coroutine to fetch the OutgoingCallerIdInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return OutgoingCallerIdPage(self._version, response, self._solution) + :returns: The fetched OutgoingCallerIdInstance + """ + return await self._proxy.fetch_async() - def get_page(self, target_url): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a specific page of OutgoingCallerIdInstance records from the API. - Request is executed immediately + Fetch the OutgoingCallerIdInstance with HTTP info - :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OutgoingCallerIdInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "OutgoingCallerIdInstance": + """ + Update the OutgoingCallerIdInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated OutgoingCallerIdInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + friendly_name=friendly_name, ) - return OutgoingCallerIdPage(self._version, response, self._solution) + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "OutgoingCallerIdInstance": + """ + Asynchronous coroutine to update the OutgoingCallerIdInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - def get(self, sid): + :returns: The updated OutgoingCallerIdInstance """ - Constructs a OutgoingCallerIdContext + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the OutgoingCallerIdInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return OutgoingCallerIdContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: """ - Constructs a OutgoingCallerIdContext + Asynchronous coroutine to update the OutgoingCallerIdInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return OutgoingCallerIdContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_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) -> tuple: """ - Build an instance of OutgoingCallerIdInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return OutgoingCallerIdInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Deletes the OutgoingCallerIdInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the OutgoingCallerIdInstance and return response metadata -class OutgoingCallerIdContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, account_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the OutgoingCallerIdContext + Internal async helper for delete operation - :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: + tuple: (success_boolean, status_code, headers) + """ - :returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdContext - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdContext + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(OutgoingCallerIdContext, self).__init__(version) + Asynchronous coroutine that deletes the OutgoingCallerIdInstance - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/OutgoingCallerIds/{sid}.json'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OutgoingCallerIdInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OutgoingCallerIdInstance: """ 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, ) + payload, _, _ = self._fetch() + return OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OutgoingCallerIdInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OutgoingCallerIdInstance: + """ + Asynchronous coroutine to fetch the OutgoingCallerIdInstance + + :returns: The fetched OutgoingCallerIdInstance + """ + payload, _, _ = await self._fetch_async() 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"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OutgoingCallerIdInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers ) - 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._update(friendly_name=friendly_name) + return OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the OutgoingCallerIdInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ - 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> OutgoingCallerIdInstance: + """ + Asynchronous coroutine to update the OutgoingCallerIdInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :returns: The updated OutgoingCallerIdInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) 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_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: """ - Deletes the OutgoingCallerIdInstance + Asynchronous coroutine to update the OutgoingCallerIdInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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'), + return OutgoingCallerIdInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class OutgoingCallerIdList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the OutgoingCallerIdList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the OutgoingCallerId resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, } + self._uri = "/Accounts/{account_sid}/OutgoingCallerIds.json".format( + **self._solution + ) - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + def stream( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OutgoingCallerIdInstance]: + """ + Streams OutgoingCallerIdInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - @property - def _proxy(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 """ - 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( + phone_number=phone_number, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) - :returns: OutgoingCallerIdContext for this OutgoingCallerIdInstance - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdContext + 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]: """ - if self._context is None: - self._context = OutgoingCallerIdContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + Asynchronously streams OutgoingCallerIdInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str phone_number: The phone number of the OutgoingCallerId resources to read. + :param str friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + phone_number=phone_number, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OutgoingCallerIdInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + phone_number=phone_number, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams OutgoingCallerIdInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + phone_number=phone_number, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OutgoingCallerIdInstance]: + """ + Lists OutgoingCallerIdInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str phone_number: The phone number of the OutgoingCallerId resources to read. + :param str friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + phone_number=phone_number, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OutgoingCallerIdInstance]: """ - :returns: The unique string that identifies 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 self._properties['sid'] - @property - def date_created(self): + 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 list_with_http_info( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + Lists OutgoingCallerIdInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + phone_number=phone_number, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['date_created'] + Asynchronously lists OutgoingCallerIdInstance and returns headers from first page - @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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + generator, status_code, headers = await self.stream_with_http_info_async( + phone_number=phone_number, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['date_updated'] + Retrieve a single page of OutgoingCallerIdInstance records from the API. + Request is executed immediately - @property - def friendly_name(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 string that you assigned to describe the resource - :rtype: unicode + data = values.of( + { + "PhoneNumber": phone_number, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OutgoingCallerIdPage(self._version, response, solution=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['friendly_name'] + Asynchronously retrieve a single page of OutgoingCallerIdInstance records from the API. + Request is executed immediately - @property - def account_sid(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 SID of the Account that created the resource - :rtype: unicode + data = values.of( + { + "PhoneNumber": phone_number, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OutgoingCallerIdPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['account_sid'] + Retrieve a single page with response metadata - @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: ApiResponse with OutgoingCallerIdPage, status code, and headers """ - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OutgoingCallerIdPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['phone_number'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with OutgoingCallerIdPage, status code, and headers """ - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OutgoingCallerIdPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 a85e42f7cb..dd8ca881f9 100644 --- a/twilio/rest/api/v2010/account/queue/__init__.py +++ b/twilio/rest/api/v2010/account/queue/__init__.py @@ -1,464 +1,1160 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): - """ """ +class QueueInstance(InstanceResource): + """ + :ivar date_updated: The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar current_size: The number of calls currently in the queue. + :ivar friendly_name: A string that you assigned to describe this resource. + :ivar uri: The URI of this resource, relative to `https://api.twilio.com`. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Queue resource. + :ivar average_wait_time: The average wait time in seconds of the members in this queue. This is calculated at the time of the request. + :ivar sid: The unique string that that we created to identify this Queue resource. + :ivar date_created: The date and time in GMT that this resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar max_size: The maximum number of calls that can be in the queue. The default is 1000 and the maximum is 5000. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.current_size: Optional[int] = deserialize.integer( + payload.get("current_size") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.uri: Optional[str] = payload.get("uri") + self.account_sid: Optional[str] = payload.get("account_sid") + self.average_wait_time: Optional[int] = deserialize.integer( + payload.get("average_wait_time") + ) + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.max_size: Optional[int] = deserialize.integer(payload.get("max_size")) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } - def __init__(self, version, account_sid): + self._context: Optional[QueueContext] = None + + @property + def _proxy(self) -> "QueueContext": """ - Initialize the QueueList + 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 this resource + :returns: QueueContext for this QueueInstance + """ + if self._context is None: + self._context = QueueContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.api.v2010.account.queue.QueueList - :rtype: twilio.rest.api.v2010.account.queue.QueueList + def delete(self) -> bool: """ - super(QueueList, self).__init__(version) + Deletes the QueueInstance - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Queues.json'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + 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 QueueInstance - :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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the QueueInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists QueueInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the QueueInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.queue.QueueInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_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, }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "QueueInstance": + """ + Asynchronous coroutine to fetch the QueueInstance - return QueuePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched QueueInstance """ - Retrieve a specific page of QueueInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the QueueInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the QueueInstance with HTTP info - return QueuePage(self._version, response, self._solution) - def create(self, friendly_name, max_size=values.unset): + :returns: ApiResponse with instance, status code, and headers """ - Create the QueueInstance + return await self._proxy.fetch_with_http_info_async() + + 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 created QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueInstance + :returns: The updated QueueInstance """ - data = values.of({'FriendlyName': friendly_name, 'MaxSize': max_size, }) + return self._proxy.update( + friendly_name=friendly_name, + max_size=max_size, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> "QueueInstance": + """ + Asynchronous coroutine to update the QueueInstance - return QueueInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. - def get(self, sid): + :returns: The updated QueueInstance """ - Constructs a QueueContext + return await self._proxy.update_async( + friendly_name=friendly_name, + max_size=max_size, + ) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the QueueInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return QueueContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + max_size=max_size, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Constructs a QueueContext + Asynchronous coroutine to update the QueueInstance with HTTP info - :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + max_size=max_size, + ) - :returns: twilio.rest.api.v2010.account.queue.QueueContext - :rtype: twilio.rest.api.v2010.account.queue.QueueContext + @property + def members(self) -> MemberList: + """ + 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) + + self._members: Optional[MemberList] = None - def get_instance(self, payload): + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of QueueInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.queue.QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return QueueInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Deletes the QueueInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the QueueInstance and return response metadata -class QueueContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, account_sid, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the QueueContext - :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 + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.queue.QueueContext - :rtype: twilio.rest.api.v2010.account.queue.QueueContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(QueueContext, self).__init__(version) + Asynchronous coroutine that deletes the QueueInstance - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Queues/{sid}.json'.format(**self._solution) - # Dependents - self._members = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success - def fetch(self): + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the QueueInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> QueueInstance: """ Fetch the QueueInstance + :returns: The fetched QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the QueueInstance and return response metadata + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> QueueInstance: + """ + Asynchronous coroutine to fetch the QueueInstance + + + :returns: The fetched QueueInstance + """ + payload, _, _ = await self._fetch_async() 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"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the QueueInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation - def update(self, friendly_name=values.unset, max_size=values.unset): + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "MaxSize": max_size, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._update(friendly_name=friendly_name, max_size=max_size) + return QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the QueueInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, max_size=max_size + ) + instance = QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "MaxSize": max_size, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Accept"] = "application/json" + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> QueueInstance: + """ + Asynchronous coroutine to update the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The updated QueueInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, max_size=max_size + ) 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_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the QueueInstance + Asynchronous coroutine to update the QueueInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, max_size=max_size + ) + instance = QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def members(self): + def members(self) -> MemberList: """ Access the members - - :returns: twilio.rest.api.v2010.account.queue.member.MemberList - :rtype: twilio.rest.api.v2010.account.queue.member.MemberList """ if self._members is None: self._members = MemberList( self._version, - account_sid=self._solution['account_sid'], - queue_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) return self._members - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class QueueInstance(InstanceResource): - """ """ +class QueuePage(Page): - def __init__(self, version, payload, account_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> QueueInstance: """ - Initialize the QueueInstance + Build an instance of QueueInstance - :returns: twilio.rest.api.v2010.account.queue.QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueInstance + :param payload: Payload response from the API """ - super(QueueInstance, self).__init__(version) - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'average_wait_time': deserialize.integer(payload.get('average_wait_time')), - 'current_size': deserialize.integer(payload.get('current_size')), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'max_size': deserialize.integer(payload.get('max_size')), - 'sid': payload.get('sid'), - 'uri': payload.get('uri'), + return QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class QueueList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the QueueList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Queue resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, } + self._uri = "/Accounts/{account_sid}/Queues.json".format(**self._solution) - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: QueueContext for this QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> QueueInstance: """ - if self._context is None: - self._context = QueueContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the QueueInstance - @property - def account_sid(self): + :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 """ - :returns: The SID of the Account that created this resource - :rtype: unicode + payload, _, _ = self._create(friendly_name=friendly_name, max_size=max_size) + return QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def create_with_http_info( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> ApiResponse: """ - return self._properties['account_sid'] + Create the QueueInstance and return response metadata - @property - def average_wait_time(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: Average wait time of members in the queue - :rtype: unicode + payload, status_code, headers = self._create( + friendly_name=friendly_name, max_size=max_size + ) + instance = QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> tuple: """ - return self._properties['average_wait_time'] + Internal async helper for create operation - @property - def current_size(self): + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> QueueInstance: """ - :returns: The number of calls currently in the queue. - :rtype: unicode + Asynchronously create the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The created QueueInstance """ - return self._properties['current_size'] + payload, _, _ = await self._create_async( + friendly_name=friendly_name, max_size=max_size + ) + return QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def date_created(self): + async def create_with_http_info_async( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> ApiResponse: """ - :returns: The RFC 2822 date and time in GMT that this resource was created - :rtype: datetime + Asynchronously create the QueueInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['date_created'] + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, max_size=max_size + ) + instance = QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def date_updated(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[QueueInstance]: """ - :returns: The RFC 2822 date and time in GMT that this resource was last updated - :rtype: datetime + Streams QueueInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['date_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[QueueInstance]: """ - :returns: A string that you assigned to describe 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['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def max_size(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The max number of calls allowed in the queue - :rtype: unicode + Streams QueueInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['max_size'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def sid(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The unique string that identifies this resource - :rtype: unicode + Asynchronously streams QueueInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['sid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def uri(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[QueueInstance]: """ - :returns: The URI of this resource, relative to `https://api.twilio.com` - :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['uri'] - def fetch(self): + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[QueueInstance]: """ - Fetch the QueueInstance + Asynchronously lists QueueInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: The fetched QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueInstance + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to 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() - def update(self, friendly_name=values.unset, max_size=values.unset): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Update the QueueInstance + Lists QueueInstance and returns headers from first page - :param unicode friendly_name: A string to describe this resource - :param unicode max_size: The max number of calls allowed in the queue - :returns: The updated QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueInstance + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._proxy.update(friendly_name=friendly_name, max_size=max_size, ) + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - def delete(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Deletes the QueueInstance + Asynchronously lists QueueInstance and returns headers from first page - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._proxy.delete() + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def members(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: """ - Access the members + 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: twilio.rest.api.v2010.account.queue.member.MemberList - :rtype: twilio.rest.api.v2010.account.queue.member.MemberList + :returns: Page of QueueInstance """ - return self._proxy.members + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> QueuePage: + """ + Asynchronously retrieve a single page of QueueInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of QueueInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return QueuePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with QueuePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = QueuePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with QueuePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = QueuePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> QueuePage: + """ + Retrieve a specific page of QueueInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of QueueInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return QueuePage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> QueuePage: + """ + Asynchronously retrieve a specific page of QueueInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of QueueInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return QueuePage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> QueueContext: + """ + Constructs a QueueContext + + :param sid: The Twilio-provided string that uniquely identifies the Queue resource to update + """ + return QueueContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> QueueContext: + """ + Constructs a QueueContext + + :param sid: The Twilio-provided string that uniquely identifies the Queue resource to update + """ + return QueueContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 ed1df73993..540befbbbe 100644 --- a/twilio/rest/api/v2010/account/queue/member.py +++ b/twilio/rest/api/v2010/account/queue/member.py @@ -1,398 +1,901 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 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") - def __init__(self, version, account_sid, queue_sid): - """ - Initialize the MemberList + self._solution = { + "account_sid": account_sid, + "queue_sid": queue_sid, + "call_sid": call_sid or self.call_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._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) + 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, 'queue_sid': queue_sid, } - self._uri = '/Accounts/{account_sid}/Queues/{queue_sid}/Members.json'.format(**self._solution) + :returns: MemberContext for this MemberInstance + """ + if self._context is None: + self._context = MemberContext( + self._version, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + return self._context - def stream(self, 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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 """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() + + async def fetch_async(self) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched MemberInstance + """ + return await self._proxy.fetch_async() - def list(self, limit=None, page_size=None): + def fetch_with_http_info(self) -> ApiResponse: """ - Lists MemberInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Fetch the MemberInstance with HTTP info - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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: ApiResponse with instance, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch_with_http_info() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of MemberInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the MemberInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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.api.v2010.account.queue.member.MemberPage + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_with_http_info_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def update( + self, url: str, method: Union[str, object] = values.unset + ) -> "MemberInstance": + """ + Update the MemberInstance - return MemberPage(self._version, response, 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 get_page(self, target_url): + :returns: The updated MemberInstance """ - Retrieve a specific page of MemberInstance records from the API. - Request is executed immediately + return self._proxy.update( + url=url, + method=method, + ) - :param str target_url: API-generated URL for the requested results page + async def update_async( + self, url: str, method: Union[str, object] = values.unset + ) -> "MemberInstance": + """ + Asynchronous coroutine to update the MemberInstance - :returns: Page of MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberPage + :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 """ - 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 get(self, call_sid): + def update_with_http_info( + self, url: str, method: Union[str, object] = values.unset + ) -> ApiResponse: """ - Constructs a MemberContext + Update the MemberInstance with HTTP info - :param call_sid: The Call SID of the resource(s) to fetch + :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: twilio.rest.api.v2010.account.queue.member.MemberContext - :rtype: twilio.rest.api.v2010.account.queue.member.MemberContext + :returns: ApiResponse with instance, status code, and headers """ - return MemberContext( - self._version, - account_sid=self._solution['account_sid'], - queue_sid=self._solution['queue_sid'], - call_sid=call_sid, + return self._proxy.update_with_http_info( + url=url, + method=method, ) - def __call__(self, call_sid): + async def update_with_http_info_async( + self, url: str, method: Union[str, object] = values.unset + ) -> ApiResponse: """ - Constructs a MemberContext + Asynchronous coroutine to update the MemberInstance with HTTP info - :param call_sid: The Call SID of the resource(s) to fetch + :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: twilio.rest.api.v2010.account.queue.member.MemberContext - :rtype: twilio.rest.api.v2010.account.queue.member.MemberContext + :returns: ApiResponse with instance, status code, and headers """ - return MemberContext( - self._version, - account_sid=self._solution['account_sid'], - queue_sid=self._solution['queue_sid'], - call_sid=call_sid, + return await self._proxy.update_with_http_info_async( + url=url, + method=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 MemberPage(Page): - """ """ +class MemberContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__( + self, version: Version, account_sid: str, queue_sid: str, call_sid: str + ): """ - Initialize the MemberPage - - :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 + Initialize the MemberContext - :returns: twilio.rest.api.v2010.account.queue.member.MemberPage - :rtype: twilio.rest.api.v2010.account.queue.member.MemberPage + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Member resource(s) to update. + :param queue_sid: The SID of the Queue in which to find the members to update. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resource(s) to update. """ - super(MemberPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def _fetch(self) -> tuple: """ - Build an instance of MemberInstance + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + headers["Accept"] = "application/json" - :returns: twilio.rest.api.v2010.account.queue.member.MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberInstance + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + payload, _, _ = self._fetch() 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 fetch_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Fetch the MemberInstance and return response metadata - :returns: Machine friendly representation - :rtype: str - """ - return '' + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) -class MemberContext(InstanceContext): - """ """ + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - def __init__(self, version, account_sid, queue_sid, call_sid): + Returns: + tuple: (payload, status_code, headers) """ - Initialize the MemberContext - :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 + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.queue.member.MemberContext - :rtype: twilio.rest.api.v2010.account.queue.member.MemberContext - """ - super(MemberContext, self).__init__(version) + headers["Accept"] = "application/json" - # 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) + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + async def fetch_async(self) -> MemberInstance: """ - Fetch the MemberInstance + Asynchronous coroutine to 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, ) - + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, url: str, method: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Url": url, + "Method": method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, url: str, method: Union[str, object] = values.unset + ) -> MemberInstance: """ Update the MemberInstance - :param unicode url: The absolute URL of the Queue resource - :param unicode method: How to pass the update request data + :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 - :rtype: twilio.rest.api.v2010.account.queue.member.MemberInstance """ - data = values.of({'Url': url, 'Method': method, }) + payload, _, _ = self._update(url=url, method=method) + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + + def update_with_http_info( + self, url: str, method: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the MemberInstance and return response metadata - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(url=url, method=method) + instance = MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, url: str, method: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Url": url, + "Method": method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, url: str, method: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: The updated MemberInstance + """ + payload, _, _ = await self._update_async(url=url, method=method) 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 __repr__(self): + async def update_with_http_info_async( + self, url: str, method: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(url=url, method=method) + instance = MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide 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 MemberInstance(InstanceResource): - """ """ +class MemberPage(Page): - def __init__(self, version, payload, account_sid, queue_sid, call_sid=None): + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: """ - Initialize the MemberInstance + Build an instance of MemberInstance - :returns: twilio.rest.api.v2010.account.queue.member.MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberInstance + :param payload: Payload response from the API """ - super(MemberInstance, self).__init__(version) - # 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'), - } + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation - # Context - self._context = None + :returns: Machine friendly representation + """ + return "" + + +class MemberList(ListResource): + + def __init__(self, version: Version, account_sid: str, queue_sid: str): + """ + Initialize the MemberList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Member resource(s) to read. + :param queue_sid: The SID of the Queue in which to find the members + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'account_sid': account_sid, - 'queue_sid': queue_sid, - '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'], + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: + """ + Asynchronously streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MemberInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MemberInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def call_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - :returns: The SID of the Call the resource is associated with - :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['call_sid'] - @property - def date_enqueued(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MemberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - :returns: The date the member was enqueued - :rtype: datetime + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_enqueued'] + Asynchronously lists MemberInstance and returns headers from first page - @property - def position(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: ApiResponse with list of instances, status code, and headers """ - :returns: This member's current position in the queue. - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['position'] + Retrieve a single page of MemberInstance 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 MemberInstance """ - :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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, solution=self._solution) + + async def 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: """ - return self._properties['uri'] + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately - @property - def wait_time(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 MemberInstance """ - :returns: The number of seconds the member has been in the queue. - :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 MemberPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['wait_time'] + Retrieve a single page with response metadata - @property - def queue_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: ApiResponse with MemberPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The SID of the Queue the member is in - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MemberPage, status code, and headers """ - return self._properties['queue_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - 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.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 = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, solution=self._solution) - def update(self, url, method=values.unset): + async def get_page_async(self, target_url: str) -> MemberPage: """ - Update the MemberInstance + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately - :param unicode url: The absolute URL of the Queue resource - :param unicode method: How to pass the update request data + :param target_url: API-generated URL for the requested results page - :returns: The updated MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberInstance + :returns: Page of MemberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, solution=self._solution) + + def get(self, call_sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resource(s) to update. """ - return self._proxy.update(url, method=method, ) + return MemberContext( + self._version, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=call_sid, + ) + + def __call__(self, call_sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resource(s) to update. + """ + return MemberContext( + self._version, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=call_sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 f08b567574..75af476b00 100644 --- a/twilio/rest/api/v2010/account/recording/__init__.py +++ b/twilio/rest/api/v2010/account/recording/__init__.py @@ -1,587 +1,1155 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): - """ """ +class RecordingInstance(InstanceResource): - def __init__(self, version, account_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 + 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 recording resource. For information on specifying the number of channels in the downloaded recording file, check out [Fetch a Recording’s media file](https://www.twilio.com/docs/voice/api/recording#download-dual-channel-media-file). + :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") - :returns: twilio.rest.api.v2010.account.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.recording.RecordingList - """ - super(RecordingList, self).__init__(version) + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Recordings.json'.format(**self._solution) + 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'], limits['page_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 delete_with_http_info(self) -> ApiResponse: """ - Retrieve a specific page of RecordingInstance records from the API. - Request is executed immediately + Deletes the RecordingInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of RecordingInstance - :rtype: twilio.rest.api.v2010.account.recording.RecordingPage + :returns: ApiResponse with success boolean, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return RecordingPage(self._version, response, self._solution) + return self._proxy.delete_with_http_info() - def get(self, sid): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Constructs a RecordingContext + Asynchronous coroutine that deletes the RecordingInstance with HTTP info - :param sid: The unique string that identifies the resource - :returns: twilio.rest.api.v2010.account.recording.RecordingContext - :rtype: twilio.rest.api.v2010.account.recording.RecordingContext + :returns: ApiResponse with success boolean, status code, and headers """ - return RecordingContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.delete_with_http_info_async() - def __call__(self, sid): + def fetch( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> "RecordingInstance": """ - Constructs a RecordingContext + 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 self._proxy.fetch( + include_soft_deleted=include_soft_deleted, + ) - def __repr__(self): + async def fetch_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> "RecordingInstance": """ - Provide a friendly representation + Asynchronous coroutine to fetch the RecordingInstance - :returns: Machine friendly representation - :rtype: str + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: The fetched RecordingInstance """ - return '' + return await self._proxy.fetch_async( + include_soft_deleted=include_soft_deleted, + ) + def fetch_with_http_info( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the RecordingInstance with HTTP info -class RecordingPage(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. - def __init__(self, version, response, solution): + :returns: ApiResponse with instance, status code, and headers """ - 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 + return self._proxy.fetch_with_http_info( + include_soft_deleted=include_soft_deleted, + ) - :returns: twilio.rest.api.v2010.account.recording.RecordingPage - :rtype: twilio.rest.api.v2010.account.recording.RecordingPage + async def fetch_with_http_info_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> ApiResponse: """ - super(RecordingPage, self).__init__(version, response) + Asynchronous coroutine to fetch the RecordingInstance with HTTP info - # Path Solution - self._solution = solution + :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. - def get_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of RecordingInstance + return await self._proxy.fetch_with_http_info_async( + include_soft_deleted=include_soft_deleted, + ) - :param dict payload: Payload response from the API + @property + def add_on_results(self) -> AddOnResultList: + """ + Access the add_on_results + """ + return self._proxy.add_on_results - :returns: twilio.rest.api.v2010.account.recording.RecordingInstance - :rtype: twilio.rest.api.v2010.account.recording.RecordingInstance + @property + def transcriptions(self) -> TranscriptionList: """ - return RecordingInstance(self._version, payload, account_sid=self._solution['account_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 RecordingContext(InstanceContext): - """ """ - def __init__(self, version, account_sid, sid): + def __init__(self, version: Version, account_sid: str, sid: str): """ 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 sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.recording.RecordingContext - :rtype: twilio.rest.api.v2010.account.recording.RecordingContext + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to fetch. """ - super(RecordingContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Recordings/{sid}.json'.format(**self._solution) + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{sid}.json".format( + **self._solution + ) - # Dependents - self._transcriptions = None - self._add_on_results = None + self._add_on_results: Optional[AddOnResultList] = None + self._transcriptions: Optional[TranscriptionList] = None - def fetch(self): + def _delete(self) -> tuple: """ - Fetch the RecordingInstance + Internal helper for delete operation - :returns: The fetched RecordingInstance - :rtype: twilio.rest.api.v2010.account.recording.RecordingInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return RecordingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers ) - def delete(self): + def delete(self) -> bool: """ Deletes the RecordingInstance + :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + success, _, _ = self._delete() + return success - @property - def transcriptions(self): + def delete_with_http_info(self) -> ApiResponse: """ - Access the transcriptions + Deletes the RecordingInstance and return response metadata - :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'], - ) - return self._transcriptions - @property - def add_on_results(self): + :returns: ApiResponse with success boolean, status code, and headers """ - Access the add_on_results + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultList - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultList + async def _delete_async(self) -> tuple: """ - 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 + Internal async helper for delete operation - def __repr__(self): + Returns: + tuple: (success_boolean, status_code, headers) """ - Provide 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({}) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) -class RecordingInstance(InstanceResource): - """ """ + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance - class Status(object): - IN_PROGRESS = "in-progress" - PAUSED = "paused" - STOPPED = "stopped" - PROCESSING = "processing" - COMPLETED = "completed" - ABSENT = "absent" - class Source(object): - DIALVERB = "DialVerb" - CONFERENCE = "Conference" - OUTBOUNDAPI = "OutboundAPI" - TRUNKING = "Trunking" - RECORDVERB = "RecordVerb" - STARTCALLRECORDINGAPI = "StartCallRecordingAPI" - STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success - 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'), - } + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance and return response metadata - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): + :returns: ApiResponse with success boolean, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :returns: RecordingContext for this RecordingInstance - :rtype: twilio.rest.api.v2010.account.recording.RecordingContext + def _fetch(self, include_soft_deleted: Union[bool, object] = values.unset) -> tuple: """ - if self._context is None: - self._context = RecordingContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + Internal helper for fetch operation - @property - def account_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def api_version(self): - """ - :returns: The API version used during the recording. - :rtype: unicode - """ - return self._properties['api_version'] + params = values.of( + { + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + } + ) - @property - def call_sid(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> RecordingInstance: """ - :returns: The SID of the Call the resource is associated with - :rtype: unicode + Fetch the RecordingInstance + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: The fetched RecordingInstance """ - return self._properties['call_sid'] + payload, _, _ = self._fetch(include_soft_deleted=include_soft_deleted) + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - @property - def conference_sid(self): + def fetch_with_http_info( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> ApiResponse: """ - :returns: The unique ID for the conference associated with the recording. - :rtype: unicode + Fetch the RecordingInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['conference_sid'] + payload, status_code, headers = self._fetch( + include_soft_deleted=include_soft_deleted + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def date_created(self): + async def _fetch_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> tuple: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['date_created'] - @property - def date_updated(self): + params = values.of( + { + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + async def fetch_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> RecordingInstance: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + Asynchronous coroutine to fetch the RecordingInstance + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: The fetched RecordingInstance """ - return self._properties['date_updated'] + payload, _, _ = await self._fetch_async( + include_soft_deleted=include_soft_deleted + ) + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - @property - def start_time(self): + async def fetch_with_http_info_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> ApiResponse: """ - :returns: The start time of the recording, given in RFC 2822 format - :rtype: datetime + Asynchronous coroutine to fetch the RecordingInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['start_time'] + payload, status_code, headers = await self._fetch_async( + include_soft_deleted=include_soft_deleted + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def duration(self): + def add_on_results(self) -> AddOnResultList: """ - :returns: The length of the recording in seconds. - :rtype: unicode + Access the add_on_results """ - return self._properties['duration'] + 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 sid(self): + def transcriptions(self) -> TranscriptionList: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Access the transcriptions """ - return self._properties['sid'] + if self._transcriptions is None: + self._transcriptions = TranscriptionList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._transcriptions - @property - def price(self): + def __repr__(self) -> str: """ - :returns: The one-time cost of creating the recording. - :rtype: unicode - """ - return self._properties['price'] + Provide a friendly representation - @property - def price_unit(self): + :returns: Machine friendly representation """ - :returns: The currency used in the price property. - :rtype: unicode + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: """ - return self._properties['price_unit'] + Build an instance of RecordingInstance - @property - def status(self): + :param payload: Payload response from the API """ - :returns: The status of the recording. - :rtype: RecordingInstance.Status + + return RecordingInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: """ - return self._properties['status'] + Provide a friendly representation - @property - def channels(self): + :returns: Machine friendly representation """ - :returns: The number of channels in the final recording file as an integer. - :rtype: unicode + return "" + + +class RecordingList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - return self._properties['channels'] + Initialize the RecordingList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resources to read. - @property - def source(self): """ - :returns: How the recording was created - :rtype: RecordingInstance.Source + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Recordings.json".format(**self._solution) + + def stream( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RecordingInstance]: """ - return self._properties['source'] + 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 error_code(self): + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: More information about why the recording is missing, if status is `absent`. - :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, + call_sid=call_sid, + conference_sid=conference_sid, + include_soft_deleted=include_soft_deleted, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RecordingInstance]: + """ + Asynchronously streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['error_code'] + 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 uri(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams RecordingInstance and returns headers from first page + + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams RecordingInstance and returns headers from first page + + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['uri'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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 encryption_details(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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: How to decrypt the recording. - :rtype: dict + Lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + call_sid=call_sid, + conference_sid=conference_sid, + include_soft_deleted=include_soft_deleted, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Asynchronously lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + call_sid=call_sid, + conference_sid=conference_sid, + include_soft_deleted=include_soft_deleted, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists RecordingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists RecordingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['encryption_details'] + Retrieve a single page of RecordingInstance records from the API. + Request is executed immediately - @property - def subresource_uris(self): + :param date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance """ - :returns: A list of related resources identified by their relative URIs - :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), + "CallSid": call_sid, + "ConferenceSid": conference_sid, + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, solution=self._solution) + + async def page_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Asynchronously retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance """ - return self._properties['subresource_uris'] + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "CallSid": call_sid, + "ConferenceSid": conference_sid, + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - def fetch(self): + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RecordingPage, status code, and headers + """ + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "CallSid": call_sid, + "ConferenceSid": conference_sid, + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RecordingPage, status code, and headers + """ + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "CallSid": call_sid, + "ConferenceSid": conference_sid, + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 2822ccb783..2104ab225d 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,858 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): - """ """ +class AddOnResultInstance(InstanceResource): - def __init__(self, version, account_sid, reference_sid): + class Status(object): + CANCELED = "canceled" + COMPLETED = "completed" + DELETED = "deleted" + FAILED = "failed" + IN_PROGRESS = "in-progress" + INIT = "init" + PROCESSING = "processing" + QUEUED = "queued" + + """ + :ivar sid: The unique string that that we created to identify the Recording AddOnResult resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult resource. + :ivar status: + :ivar add_on_sid: The SID of the Add-on to which the result belongs. + :ivar add_on_configuration_sid: The SID of the Add-on configuration. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_completed: The date and time in GMT that the result was completed specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar reference_sid: The SID of the recording to which the AddOnResult resource belongs. + :ivar subresource_uris: A list of related resources identified by their relative URIs. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + reference_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional["AddOnResultInstance.Status"] = payload.get("status") + self.add_on_sid: Optional[str] = payload.get("add_on_sid") + self.add_on_configuration_sid: Optional[str] = payload.get( + "add_on_configuration_sid" + ) + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.date_completed: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_completed") + ) + self.reference_sid: Optional[str] = payload.get("reference_sid") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "sid": sid or self.sid, + } + + self._context: Optional[AddOnResultContext] = None + + @property + def _proxy(self) -> "AddOnResultContext": """ - Initialize the AddOnResultList + 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 belongs + :returns: AddOnResultContext for this AddOnResultInstance + """ + if self._context is None: + self._context = AddOnResultContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultList - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultList + def delete(self) -> bool: """ - super(AddOnResultList, self).__init__(version) + Deletes the AddOnResultInstance - # Path Solution - self._solution = {'account_sid': account_sid, 'reference_sid': reference_sid, } - self._uri = '/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults.json'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + 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 AddOnResultInstance - :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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AddOnResultInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists AddOnResultInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddOnResultInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "AddOnResultInstance": """ - Retrieve a single page of AddOnResultInstance records from the API. - Request is executed immediately + Fetch 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: The fetched AddOnResultInstance """ - 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) -> "AddOnResultInstance": + """ + Asynchronous coroutine to fetch the AddOnResultInstance - return AddOnResultPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched AddOnResultInstance """ - Retrieve a specific page of AddOnResultInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AddOnResultInstance with HTTP info - :returns: Page of AddOnResultInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AddOnResultInstance with HTTP info - return AddOnResultPage(self._version, response, self._solution) - def get(self, sid): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a AddOnResultContext + return await self._proxy.fetch_with_http_info_async() - :param sid: The unique string that identifies the resource to fetch + @property + def payloads(self) -> PayloadList: + """ + Access the payloads + """ + return self._proxy.payloads - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext + def __repr__(self) -> str: """ - return AddOnResultContext( - self._version, - account_sid=self._solution['account_sid'], - reference_sid=self._solution['reference_sid'], - sid=sid, - ) + Provide a friendly representation - def __call__(self, sid): + :returns: Machine friendly representation """ - Constructs a AddOnResultContext + 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 AddOnResultContext(InstanceContext): - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext + def __init__( + self, version: Version, account_sid: str, reference_sid: str, sid: str + ): """ - return AddOnResultContext( - self._version, - account_sid=self._solution['account_sid'], - reference_sid=self._solution['reference_sid'], - sid=sid, + Initialize the AddOnResultContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult resource to fetch. + :param reference_sid: The SID of the recording to which the result to fetch belongs. + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults/{sid}.json".format( + **self._solution ) - def __repr__(self): + self._payloads: Optional[PayloadList] = None + + def _delete(self) -> tuple: """ - Provide a friendly representation + Internal helper for delete operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (success_boolean, status_code, headers) """ - return '' + headers = values.of({}) -class AddOnResultPage(Page): - """ """ + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def delete(self) -> bool: """ - Initialize the AddOnResultPage + Deletes the AddOnResultInstance - :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 - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultPage - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultPage + :returns: True if delete succeeds, False otherwise """ - super(AddOnResultPage, self).__init__(version, response) + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AddOnResultInstance and return response metadata - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: ApiResponse with success boolean, status code, and headers """ - Build an instance of AddOnResultInstance + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - return AddOnResultInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - reference_sid=self._solution['reference_sid'], + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the AddOnResultInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddOnResultInstance and return response metadata -class AddOnResultContext(InstanceContext): - """ """ - def __init__(self, version, account_sid, reference_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the AddOnResultContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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 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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext + Returns: + tuple: (payload, status_code, headers) """ - 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 + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", 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, ) + payload, _, _ = self._fetch() + return AddOnResultInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AddOnResultInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AddOnResultInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AddOnResultInstance: + """ + Asynchronous coroutine to fetch the AddOnResultInstance + + :returns: The fetched AddOnResultInstance + """ + payload, _, _ = await self._fetch_async() 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_with_http_info_async(self) -> ApiResponse: """ - Deletes the AddOnResultInstance + Asynchronous coroutine to fetch the AddOnResultInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = AddOnResultInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance + return AddOnResultInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + ) + + 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 "" + + +class AddOnResultList(ListResource): + + def __init__(self, version: Version, account_sid: str, reference_sid: str): + """ + Initialize the AddOnResultList - # Context - self._context = None + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult resources to read. + :param reference_sid: The SID of the recording to which the result to read belongs. + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'account_sid': account_sid, - 'reference_sid': reference_sid, - 'sid': sid or self._properties['sid'], + "account_sid": account_sid, + "reference_sid": reference_sid, } + self._uri = "/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults.json".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AddOnResultInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: AddOnResultContext for this AddOnResultInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = AddOnResultContext( - self._version, - account_sid=self._solution['account_sid'], - reference_sid=self._solution['reference_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[AddOnResultInstance]: """ - :returns: The unique string that identifies the resource - :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['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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Streams AddOnResultInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def status(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The status of the result - :rtype: AddOnResultInstance.Status + Asynchronously streams AddOnResultInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['status'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def add_on_sid(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddOnResultInstance]: """ - :returns: The SID of the Add-on to which the result belongs - :rtype: unicode + 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['add_on_sid'] - @property - def add_on_configuration_sid(self): + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddOnResultInstance]: """ - :returns: The SID of the Add-on configuration - :rtype: unicode + 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['add_on_configuration_sid'] - @property - def date_created(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + Lists AddOnResultInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_created'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def date_updated(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + Asynchronously lists AddOnResultInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_updated'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: A list of related resources identified by their relative URIs - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AddOnResultPage, status code, and headers """ - return self._properties['subresource_uris'] + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AddOnResultPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Fetch the AddOnResultInstance + Asynchronously retrieve a single page with response metadata - :returns: The fetched AddOnResultInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AddOnResultPage, status code, and headers """ - 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 delete(self): + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AddOnResultPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> AddOnResultPage: """ - Deletes the AddOnResultInstance + Retrieve a specific page of AddOnResultInstance 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 AddOnResultInstance """ - return self._proxy.delete() + response = self._version.domain.twilio.request("GET", target_url) + return AddOnResultPage(self._version, response, solution=self._solution) - @property - def payloads(self): + async def get_page_async(self, target_url: str) -> AddOnResultPage: """ - Access the payloads + Asynchronously retrieve a specific page of AddOnResultInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadList - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadList + :returns: Page of AddOnResultInstance """ - return self._proxy.payloads + response = await self._version.domain.twilio.request_async("GET", target_url) + return AddOnResultPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> AddOnResultContext: + """ + Constructs a AddOnResultContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult resource to fetch. + """ + return AddOnResultContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AddOnResultContext: + """ + Constructs a AddOnResultContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult resource to fetch. + """ + return AddOnResultContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 2055200903..cabc10f323 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,873 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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" + ) + + 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 - def __init__(self, version, account_sid, reference_sid, add_on_result_sid): + @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 + + :returns: PayloadContext for this PayloadInstance + """ + if self._context is None: + self._context = PayloadContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PayloadInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PayloadInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PayloadInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PayloadInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "PayloadInstance": + """ + Fetch the PayloadInstance + + + :returns: The fetched PayloadInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PayloadInstance": + """ + Asynchronous coroutine to fetch the PayloadInstance + + + :returns: The fetched PayloadInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PayloadInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PayloadInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + @property + def data(self) -> DataList: + """ + Access the data + """ + return self._proxy.data + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PayloadContext(InstanceContext): - :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 + def __init__( + self, + version: Version, + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + sid: str, + ): + """ + Initialize the PayloadContext - :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 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(PayloadList, 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, + "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.json'.format(**self._solution) + self._uri = "/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults/{add_on_result_sid}/Payloads/{sid}.json".format( + **self._solution + ) - def stream(self, limit=None, page_size=None): + self._data: Optional[DataList] = None + + def _delete(self) -> tuple: """ - 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. + Internal helper for delete operation - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadInstance] + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the PayloadInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success - def list(self, limit=None, page_size=None): + def delete_with_http_info(self) -> ApiResponse: """ - Lists PayloadInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the PayloadInstance and return response metadata - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def _delete_async(self) -> tuple: """ - Retrieve a single page of PayloadInstance records from the API. - Request is executed immediately + Internal async helper for delete operation - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: Page of PayloadInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadPage + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Asynchronous coroutine that deletes the PayloadInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return PayloadPage(self._version, response, self._solution) + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success - def get_page(self, target_url): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Retrieve a specific page of PayloadInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the PayloadInstance and return response metadata - :param str target_url: API-generated URL for the requested results page - :returns: Page of PayloadInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadPage + :returns: ApiResponse with success boolean, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - return PayloadPage(self._version, response, self._solution) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - def get(self, sid): + Returns: + tuple: (payload, status_code, headers) """ - Constructs a PayloadContext - :param sid: The unique string that identifies the resource to fetch + headers = values.of({}) + + headers["Accept"] = "application/json" - :returns: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadContext - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadContext + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PayloadInstance: """ - return PayloadContext( + Fetch the PayloadInstance + + + :returns: The fetched PayloadInstance + """ + payload, _, _ = self._fetch() + 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 __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a PayloadContext + Fetch the PayloadInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return PayloadContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class PayloadPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> PayloadInstance: """ - Initialize the PayloadPage + Asynchronous coroutine to fetch the PayloadInstance + - :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 + :returns: The fetched PayloadInstance + """ + payload, _, _ = await self._fetch_async() + 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"], + ) - :returns: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadPage - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadPage + async def fetch_with_http_info_async(self) -> ApiResponse: """ - super(PayloadPage, self).__init__(version, response) + Asynchronous coroutine to fetch the PayloadInstance and return response metadata - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of PayloadInstance + payload, status_code, headers = await self._fetch_async() + instance = 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 ApiResponse(data=instance, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + @property + def data(self) -> DataList: + """ + Access the data + """ + if self._data is None: + self._data = DataList( + self._version, + self._solution["account_sid"], + self._solution["reference_sid"], + self._solution["add_on_result_sid"], + self._solution["sid"], + ) + return self._data - :returns: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadInstance + def __repr__(self) -> str: """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PayloadPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PayloadInstance: + """ + Build an instance of PayloadInstance + + :param payload: Payload response from the API + """ + return PayloadInstance( self._version, payload, - account_sid=self._solution['account_sid'], - reference_sid=self._solution['reference_sid'], - add_on_result_sid=self._solution['add_on_result_sid'], + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PayloadInstance and returns headers from first page -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'), - } - # 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'], - } + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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: tuple of (generator, status_code, headers) where generator yields instances """ - 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_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: PayloadContext for this PayloadInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadContext - """ - 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 + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - @property - def sid(self): + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Asynchronously streams PayloadInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['sid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def add_on_result_sid(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PayloadInstance]: """ - :returns: The SID of the AddOnResult to which the payload belongs - :rtype: unicode + Lists PayloadInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['add_on_result_sid'] - @property - def account_sid(self): + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PayloadInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Asynchronously lists PayloadInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['account_sid'] - @property - def label(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The string that describes the payload - :rtype: unicode + Lists PayloadInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['label'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def add_on_sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Add-on to which the result belongs - :rtype: unicode + Asynchronously lists PayloadInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['add_on_sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def add_on_configuration_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 SID of the Add-on configuration - :rtype: unicode + Retrieve a single page of PayloadInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PayloadInstance """ - return self._properties['add_on_configuration_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def content_type(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 PayloadPage(self._version, response, solution=self._solution) + + async def 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 + Asynchronously retrieve a single page of PayloadInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PayloadInstance """ - return self._properties['content_type'] + 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 PayloadPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PayloadPage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PayloadPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PayloadPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PayloadPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..e0847813c0 --- /dev/null +++ b/twilio/rest/api/v2010/account/recording/add_on_result/payload/data.py @@ -0,0 +1,321 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DataInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DataInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DataInstance: + """ + Fetch the DataInstance + + + :returns: The fetched DataInstance + """ + payload, _, _ = self._fetch() + 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DataInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = 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"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DataInstance: + """ + Asynchronous coroutine to fetch the DataInstance + + + :returns: The fetched DataInstance + """ + payload, _, _ = await self._fetch_async() + 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DataInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = 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"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 bcd048e6fe..166d49f641 100644 --- a/twilio/rest/api/v2010/account/recording/transcription.py +++ b/twilio/rest/api/v2010/account/recording/transcription.py @@ -1,450 +1,829 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + + class Status(object): + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + FAILED = "failed" - def __init__(self, version, account_sid, recording_sid): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resource. + :ivar api_version: The API version used to create the transcription. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar duration: The duration of the transcribed audio in seconds. + :ivar price: The charge for the transcript in the currency associated with the account. This value is populated after the transcript is complete so it may not be available immediately. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar recording_sid: The SID of the [Recording](https://www.twilio.com/docs/voice/api/recording) from which the transcription was created. + :ivar sid: The unique string that that we created to identify the Transcription resource. + :ivar status: + :ivar transcription_text: The text content of the transcription. + :ivar type: The transcription type. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + recording_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.duration: Optional[str] = payload.get("duration") + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.recording_sid: Optional[str] = payload.get("recording_sid") + self.sid: Optional[str] = payload.get("sid") + self.status: Optional["TranscriptionInstance.Status"] = payload.get("status") + self.transcription_text: Optional[str] = payload.get("transcription_text") + self.type: Optional[str] = payload.get("type") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "recording_sid": recording_sid, + "sid": sid or self.sid, + } + + self._context: Optional[TranscriptionContext] = None + + @property + def _proxy(self) -> "TranscriptionContext": """ - Initialize the TranscriptionList + 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 recording_sid: The SID that identifies the transcription's recording + :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: twilio.rest.api.v2010.account.recording.transcription.TranscriptionList - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionList + def delete(self) -> bool: """ - super(TranscriptionList, self).__init__(version) + Deletes the TranscriptionInstance - # Path Solution - self._solution = {'account_sid': account_sid, 'recording_sid': recording_sid, } - self._uri = '/Accounts/{account_sid}/Recordings/{recording_sid}/Transcriptions.json'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + 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 TranscriptionInstance - :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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptionInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists TranscriptionInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptionInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_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() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionPage + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionInstance with HTTP info - return TranscriptionPage(self._version, response, self._solution) - def get(self, sid): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a TranscriptionContext + return await self._proxy.fetch_with_http_info_async() - :param sid: The unique string that identifies the resource + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionContext - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionContext + :returns: Machine friendly representation """ - return TranscriptionContext( - self._version, - account_sid=self._solution['account_sid'], - recording_sid=self._solution['recording_sid'], - sid=sid, + 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, recording_sid: str, sid: str + ): + """ + Initialize the TranscriptionContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resource to fetch. + :param recording_sid: The SID of the [Recording](https://www.twilio.com/docs/voice/api/recording) that created the transcription to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "recording_sid": recording_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{recording_sid}/Transcriptions/{sid}.json".format( + **self._solution ) - def __call__(self, sid): + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Constructs a TranscriptionContext - :param sid: The unique string that identifies the resource + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionContext - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionContext + def delete(self) -> bool: """ - return TranscriptionContext( - self._version, - account_sid=self._solution['account_sid'], - recording_sid=self._solution['recording_sid'], - sid=sid, + Deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + 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 '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptionInstance and return response metadata -class TranscriptionPage(Page): - """ """ - def __init__(self, version, response, solution): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the TranscriptionPage + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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 the resource - :param recording_sid: The SID that identifies the transcription's recording + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionPage - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionPage + Returns: + tuple: (payload, status_code, headers) """ - super(TranscriptionPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) + + headers["Accept"] = "application/json" - def get_instance(self, payload): + return self._version.fetch_with_response_info( + method="GET", 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.recording.transcription.TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance + :returns: The fetched TranscriptionInstance """ + payload, _, _ = self._fetch() 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Fetch the TranscriptionInstance and return response metadata - :returns: Machine friendly representation - :rtype: str - """ - return '' + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) -class TranscriptionContext(InstanceContext): - """ """ + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - def __init__(self, version, account_sid, recording_sid, sid): + Returns: + tuple: (payload, status_code, headers) """ - Initialize the TranscriptionContext - :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 + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionContext - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionContext - """ - super(TranscriptionContext, self).__init__(version) + headers["Accept"] = "application/json" - # 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) + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + async def fetch_async(self) -> TranscriptionInstance: """ - Fetch the TranscriptionInstance + Asynchronous coroutine to fetch the TranscriptionInstance + :returns: The fetched TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - + payload, _, _ = await self._fetch_async() 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"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the TranscriptionInstance + Asynchronous coroutine to fetch the TranscriptionInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 TranscriptionInstance(InstanceResource): - """ """ +class TranscriptionPage(Page): - class Status(object): - IN_PROGRESS = "in-progress" - COMPLETED = "completed" - FAILED = "failed" + def get_instance(self, payload: Dict[str, Any]) -> TranscriptionInstance: + """ + Build an instance of TranscriptionInstance - 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 payload: Payload response from the API + """ + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TranscriptionList(ListResource): + + def __init__(self, version: Version, account_sid: str, recording_sid: str): + """ + Initialize the TranscriptionList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resources to read. + :param recording_sid: The SID of the [Recording](https://www.twilio.com/docs/voice/api/recording) that created the transcriptions to read. + + """ + super().__init__(version) - # Context - self._context = None + # Path Solution self._solution = { - 'account_sid': account_sid, - 'recording_sid': recording_sid, - 'sid': sid or self._properties['sid'], + "account_sid": account_sid, + "recording_sid": recording_sid, } + self._uri = "/Accounts/{account_sid}/Recordings/{recording_sid}/Transcriptions.json".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TranscriptionInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Streams TranscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :returns: TranscriptionContext for this TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionContext + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = TranscriptionContext( - self._version, - account_sid=self._solution['account_sid'], - recording_sid=self._solution['recording_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 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[TranscriptionInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Asynchronously streams TranscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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 api_version(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The API version used to create the transcription - :rtype: unicode + Streams TranscriptionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['api_version'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def date_created(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + Asynchronously streams TranscriptionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def date_updated(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + 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['date_updated'] - @property - def duration(self): + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: """ - :returns: The duration of the transcribed audio in seconds. - :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['duration'] - @property - def price(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The charge for the transcription - :rtype: unicode + Lists TranscriptionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['price'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def price_unit(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The currency in which price is measured - :rtype: unicode + Asynchronously lists TranscriptionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['price_unit'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def recording_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, + ) -> TranscriptionPage: """ - :returns: The SID that identifies the transcription's recording - :rtype: unicode + 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['recording_sid'] + 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 TranscriptionPage(self._version, response, solution=self._solution) + + async def 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 unique string that identifies the resource - :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['sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def status(self): + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The status of the transcription - :rtype: TranscriptionInstance.Status + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptionPage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TranscriptionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The text content of the transcription. - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptionPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TranscriptionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 4dee12b844..c1c2e3f689 100644 --- a/twilio/rest/api/v2010/account/short_code.py +++ b/twilio/rest/api/v2010/account/short_code.py @@ -1,473 +1,1111 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 + 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 this resource + :returns: ShortCodeContext for this ShortCodeInstance + """ + if self._context is None: + self._context = ShortCodeContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.api.v2010.account.short_code.ShortCodeList - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList + def fetch(self) -> "ShortCodeInstance": """ - super(ShortCodeList, self).__init__(version) + Fetch the ShortCodeInstance - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/SMS/ShortCodes.json'.format(**self._solution) - def stream(self, friendly_name=values.unset, short_code=values.unset, - limit=None, page_size=None): + :returns: The fetched ShortCodeInstance """ - Streams ShortCodeInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param 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) + return self._proxy.fetch() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.short_code.ShortCodeInstance] + async def fetch_async(self) -> "ShortCodeInstance": """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine to fetch the ShortCodeInstance - page = self.page(friendly_name=friendly_name, short_code=short_code, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched ShortCodeInstance + """ + return await self._proxy.fetch_async() - def list(self, friendly_name=values.unset, short_code=values.unset, limit=None, - page_size=None): + def fetch_with_http_info(self) -> ApiResponse: """ - Lists ShortCodeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Fetch the ShortCodeInstance with HTTP info - :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] + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream( - friendly_name=friendly_name, - short_code=short_code, - limit=limit, - page_size=page_size, - )) + return self._proxy.fetch_with_http_info() - def page(self, friendly_name=values.unset, short_code=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of ShortCodeInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ShortCodeInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'FriendlyName': friendly_name, - 'ShortCode': short_code, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return await self._proxy.fetch_with_http_info_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> "ShortCodeInstance": + """ + Update the ShortCodeInstance - 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 update_with_http_info( + 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, + ) -> ApiResponse: """ - Constructs a ShortCodeContext + Update the ShortCodeInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return ShortCodeContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + api_version=api_version, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + ) - def __call__(self, sid): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Constructs a ShortCodeContext + Asynchronous coroutine to update the ShortCodeInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return ShortCodeContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + api_version=api_version, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ShortCodePage(Page): - """ """ +class ShortCodeContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the ShortCodePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The SID of the Account that created this resource + Initialize the ShortCodeContext - :returns: twilio.rest.api.v2010.account.short_code.ShortCodePage - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodePage + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource(s) to update. + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update """ - super(ShortCodePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SMS/ShortCodes/{sid}.json".format( + **self._solution + ) - def get_instance(self, payload): + def _fetch(self) -> tuple: """ - Build an instance of ShortCodeInstance + Internal helper for fetch operation - :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: + tuple: (payload, status_code, headers) """ - return ShortCodeInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ShortCodeInstance: """ - Provide a friendly representation + Fetch the ShortCodeInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched ShortCodeInstance """ - return '' + payload, _, _ = self._fetch() + return ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ShortCodeInstance and return response metadata -class ShortCodeContext(InstanceContext): - """ """ - def __init__(self, version, account_sid, sid): + :returns: ApiResponse with instance, status code, and headers """ - Initialize the ShortCodeContext + payload, status_code, headers = self._fetch() + instance = ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 sid: The unique string that identifies this resource + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: twilio.rest.api.v2010.account.short_code.ShortCodeContext - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeContext + Returns: + tuple: (payload, status_code, headers) """ - super(ShortCodeContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/SMS/ShortCodes/{sid}.json'.format(**self._solution) + headers = values.of({}) - def fetch(self): + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ShortCodeInstance: """ - Fetch the ShortCodeInstance + Asynchronous coroutine to fetch the ShortCodeInstance + :returns: The fetched ShortCodeInstance - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ShortCodeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> ShortCodeInstance: """ Update the ShortCodeInstance - :param unicode friendly_name: A 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 + :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._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 ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ShortCodeInstance and return response metadata - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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 ShortCodeInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ShortCodeInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 - @property - def account_sid(self): + return ShortCodeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: """ - :returns: The SID of the Account that created this resource - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def api_version(self): + +class ShortCodeList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - :returns: The API version used to start a new TwiML session - :rtype: unicode + 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. + """ - return self._properties['api_version'] + super().__init__(version) - @property - def date_created(self): + # 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]: """ - :returns: The RFC 2822 date and time in GMT that this resource was created - :rtype: datetime + Streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the ShortCode resources to read. + :param str short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page = self.page( + friendly_name=friendly_name, + short_code=short_code, + page_size=limits["page_size"], + ) - @property - def date_updated(self): + 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]: """ - :returns: The RFC 2822 date and time in GMT that this resource was last updated - :rtype: datetime + Asynchronously streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param 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 """ - return self._properties['date_updated'] + 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"], + ) - @property - def friendly_name(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: A string that you assigned to describe this resource - :rtype: unicode + Streams ShortCodeInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, + short_code=short_code, + page_size=limits["page_size"], + ) - @property - def short_code(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - :returns: The short code. e.g., 894546. - :rtype: unicode + Asynchronously streams ShortCodeInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['short_code'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, + short_code=short_code, + page_size=limits["page_size"], + ) - @property - def sid(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - :returns: The unique string that identifies this resource - :rtype: unicode + 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 self._properties['sid'] - @property - def sms_fallback_method(self): + 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: HTTP method we use to call the sms_fallback_url - :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 list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['sms_fallback_method'] + Lists ShortCodeInstance and returns headers from first page - @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: ApiResponse with list of instances, status code, and headers """ - :returns: URL Twilio will request if an error occurs in executing TwiML - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + short_code=short_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['sms_fallback_url'] + Asynchronously lists ShortCodeInstance and returns headers from first page - @property - def sms_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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - :returns: HTTP method to use when requesting the sms url - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + short_code=short_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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_method'] + 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 + """ + 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, solution=self._solution) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ShortCodePage: + """ + Asynchronously retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the ShortCode resources to read. + :param short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ShortCodeInstance """ - :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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ShortCodePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ShortCodePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ShortCodePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ShortCodePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 75a6ff56a3..64ba733192 100644 --- a/twilio/rest/api/v2010/account/signing_key.py +++ b/twilio/rest/api/v2010/account/signing_key.py @@ -1,371 +1,961 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +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") + ) - def __init__(self, version, account_sid): + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + + self._context: Optional[SigningKeyContext] = None + + @property + def _proxy(self) -> "SigningKeyContext": """ - Initialize the SigningKeyList + 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: SigningKeyContext for this SigningKeyInstance + """ + if self._context is None: + self._context = SigningKeyContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyList - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyList + def delete(self) -> bool: """ - super(SigningKeyList, self).__init__(version) + Deletes the SigningKeyInstance - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/SigningKeys.json'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: """ - 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. + Asynchronous coroutine that deletes the SigningKeyInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SigningKeyInstance with HTTP info - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() - def list(self, limit=None, page_size=None): + async def delete_with_http_info_async(self) -> ApiResponse: """ - 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 with HTTP info - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_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, }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "SigningKeyInstance": + """ + Asynchronous coroutine to fetch the SigningKeyInstance - return SigningKeyPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched SigningKeyInstance """ - Retrieve a specific page of SigningKeyInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SigningKeyInstance with HTTP info - :returns: Page of SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyPage + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SigningKeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "SigningKeyInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Update the SigningKeyInstance + + :param friendly_name: + + :returns: The updated SigningKeyInstance + """ + return self._proxy.update( + friendly_name=friendly_name, ) - return SigningKeyPage(self._version, response, self._solution) + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "SigningKeyInstance": + """ + Asynchronous coroutine to update the SigningKeyInstance + + :param friendly_name: - def get(self, sid): + :returns: The updated SigningKeyInstance """ - Constructs a SigningKeyContext + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - :param sid: The sid + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the SigningKeyInstance with HTTP info + + :param friendly_name: - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyContext - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyContext + :returns: ApiResponse with instance, status code, and headers """ - return SigningKeyContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: """ - Constructs a SigningKeyContext + Asynchronous coroutine to update the SigningKeyInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return SigningKeyContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of SigningKeyInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return SigningKeyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Deletes the SigningKeyInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the SigningKeyInstance and return response metadata -class SigningKeyContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, account_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the SigningKeyContext + Internal async helper for delete operation - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: The sid + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyContext - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyContext + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(SigningKeyContext, self).__init__(version) + Asynchronous coroutine that deletes the SigningKeyInstance - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/SigningKeys/{sid}.json'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SigningKeyInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SigningKeyInstance: """ 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, ) + payload, _, _ = self._fetch() + return SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SigningKeyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SigningKeyInstance: + """ + Asynchronous coroutine to fetch the SigningKeyInstance + + + :returns: The fetched SigningKeyInstance + """ + payload, _, _ = await self._fetch_async() 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"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SigningKeyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def update(self, friendly_name=values.unset): + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._update(friendly_name=friendly_name) + return SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the SigningKeyInstance and return response metadata + + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> SigningKeyInstance: + """ + Asynchronous coroutine to update the SigningKeyInstance - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :param friendly_name: + :returns: The updated SigningKeyInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) 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_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: """ - Deletes the SigningKeyInstance + Asynchronous coroutine to update the SigningKeyInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 + + :returns: Machine friendly representation + """ + return "" + - def __init__(self, version, payload, account_sid, sid=None): +class SigningKeyList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - Initialize the SigningKeyInstance + 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'], + Asynchronously streams SigningKeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SigningKeyInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SigningKeyInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SigningKeyInstance]: + """ + Lists SigningKeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SigningKeyInstance]: """ - :returns: The sid - :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['sid'] - @property - def friendly_name(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The friendly_name - :rtype: unicode + Lists SigningKeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['friendly_name'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def date_created(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The date_created - :rtype: datetime + Asynchronously lists SigningKeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_created'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> SigningKeyPage: """ - :returns: The date_updated - :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_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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SigningKeyPage(self._version, response, solution=self._solution) + + async def 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: """ - Fetch the SigningKeyInstance + Asynchronously retrieve a single 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 page_token: PageToken provided by the API + :param page_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._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 update(self, friendly_name=values.unset): + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SigningKeyPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Update the SigningKeyInstance + Retrieve a single page with response metadata - :param unicode friendly_name: The friendly_name - :returns: The updated SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SigningKeyPage, status code, and headers """ - return self._proxy.update(friendly_name=friendly_name, ) + data = values.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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SigningKeyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the SigningKeyInstance + Asynchronously retrieve a single page with response metadata - :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: ApiResponse with SigningKeyPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SigningKeyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> SigningKeyPage: + """ + Retrieve a specific page of SigningKeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SigningKeyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SigningKeyPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> SigningKeyPage: + """ + Asynchronously retrieve a specific page of SigningKeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SigningKeyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SigningKeyPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> SigningKeyContext: + """ + Constructs a SigningKeyContext + + :param sid: + """ + return SigningKeyContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> SigningKeyContext: + """ + Constructs a SigningKeyContext + + :param sid: + """ + return SigningKeyContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 ac69aefad4..0aef74f3b0 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,1078 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): - """ """ +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") - def __init__(self, version, account_sid): + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + + self._context: Optional[CredentialListContext] = None + + @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 account_sid: A 34 character string that uniquely identifies this resource. + :returns: CredentialListContext for this CredentialListInstance + """ + if self._context is None: + self._context = CredentialListContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListList - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListList + def delete(self) -> bool: """ - super(CredentialListList, self).__init__(version) + Deletes the CredentialListInstance - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/SIP/CredentialLists.json'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + 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 CredentialListInstance - :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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialListInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists CredentialListInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_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, }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "CredentialListInstance": + """ + Asynchronous coroutine to fetch the CredentialListInstance - return CredentialListPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched CredentialListInstance """ - Retrieve a specific page of CredentialListInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialListInstance with HTTP info - :returns: Page of CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() - return CredentialListPage(self._version, response, self._solution) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialListInstance with HTTP info - def create(self, friendly_name): + + :returns: ApiResponse with instance, status code, and headers """ - Create the CredentialListInstance + return await self._proxy.fetch_with_http_info_async() - :param unicode friendly_name: Human readable descriptive text + def update(self, friendly_name: str) -> "CredentialListInstance": + """ + Update the CredentialListInstance - :returns: The created CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: The updated CredentialListInstance """ - data = values.of({'FriendlyName': friendly_name, }) + return self._proxy.update( + friendly_name=friendly_name, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def update_async(self, friendly_name: str) -> "CredentialListInstance": + """ + Asynchronous coroutine to update the CredentialListInstance - return CredentialListInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. - def get(self, sid): + :returns: The updated CredentialListInstance """ - Constructs a CredentialListContext + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - :param sid: Fetch by unique credential list Sid + def update_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Update the CredentialListInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers """ - return CredentialListContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: """ - Constructs a CredentialListContext + Asynchronous coroutine to update the CredentialListInstance with HTTP info + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. - :param sid: Fetch by unique credential list Sid + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) - :returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext + @property + def credentials(self) -> CredentialList: + """ + 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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of CredentialListInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return CredentialListInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Deletes the CredentialListInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the CredentialListInstance and return response metadata -class CredentialListContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, account_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the CredentialListContext + Internal async helper for delete operation - :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: + tuple: (success_boolean, status_code, headers) + """ - :returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(CredentialListContext, self).__init__(version) + Asynchronous coroutine that deletes the CredentialListInstance - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/SIP/CredentialLists/{sid}.json'.format(**self._solution) - # Dependents - self._credentials = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - def fetch(self): + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialListInstance: """ 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, ) + payload, _, _ = self._fetch() + return CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialListInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CredentialListInstance: + """ + Asynchronous coroutine to fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + payload, _, _ = await self._fetch_async() 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"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialListInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers ) - 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._update(friendly_name=friendly_name) + return CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Update the CredentialListInstance and return response metadata + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Accept"] = "application/json" + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async(self, friendly_name: str) -> CredentialListInstance: + """ + Asynchronous coroutine to update the CredentialListInstance + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: The updated CredentialListInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) 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_with_http_info_async(self, friendly_name: str) -> ApiResponse: """ - Deletes the CredentialListInstance + Asynchronous coroutine to update the CredentialListInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 + + :param payload: Payload response from the API + """ + + return CredentialListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" - def __init__(self, version, payload, account_sid, sid=None): + +class CredentialListList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - Initialize the CredentialListInstance + 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: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance """ - super(CredentialListInstance, self).__init__(version) + super().__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'), - 'subresource_uris': payload.get('subresource_uris'), - 'uri': payload.get('uri'), + # Path Solution + self._solution = { + "account_sid": account_sid, } + self._uri = "/Accounts/{account_sid}/SIP/CredentialLists.json".format( + **self._solution + ) - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + def _create(self, friendly_name: str) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: CredentialListContext for this CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, friendly_name: str) -> CredentialListInstance: """ - if self._context is None: - self._context = CredentialListContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + Create the CredentialListInstance + + :param friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. + + :returns: The created CredentialListInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) + return CredentialListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def create_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Create the CredentialListInstance and return response metadata + + :param friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = CredentialListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, friendly_name: str) -> CredentialListInstance: + """ + Asynchronously create the CredentialListInstance + + :param friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. + + :returns: The created CredentialListInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return CredentialListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronously create the CredentialListInstance and return response metadata + + :param friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = CredentialListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialListInstance]: + """ + Streams CredentialListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialListInstance]: + """ + Asynchronously streams CredentialListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialListInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialListInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: + """ + Lists CredentialListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def account_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: """ - :returns: The unique sid that identifies this account - :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['account_sid'] - @property - def date_created(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The date this resource was created - :rtype: datetime + Lists CredentialListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_created'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def date_updated(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The date this resource was last updated - :rtype: datetime + Asynchronously lists CredentialListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_updated'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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: Human readable descriptive text - :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 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 CredentialListPage(self._version, response, solution=self._solution) + + async def 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: A string that uniquely identifies this credential - :rtype: unicode + Asynchronously retrieve a single page of CredentialListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialListInstance """ - return self._properties['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 CredentialListPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The list of credentials associated with this credential list. - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialListPage, status code, and headers """ - return self._properties['subresource_uris'] + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The URI for this resource - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialListPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> CredentialListPage: """ - Fetch the CredentialListInstance + Retrieve a specific 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 target_url: API-generated URL for the requested results page + + :returns: Page of CredentialListInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return CredentialListPage(self._version, response, solution=self._solution) - def update(self, friendly_name): + async def get_page_async(self, target_url: str) -> CredentialListPage: """ - Update the CredentialListInstance + Asynchronously retrieve a specific page of CredentialListInstance records from the API. + Request is executed immediately - :param unicode friendly_name: 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 = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialListPage(self._version, response, solution=self._solution) - def delete(self): + def get(self, sid: str) -> CredentialListContext: """ - Deletes the CredentialListInstance + Constructs a CredentialListContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The credential list Sid that uniquely identifies this resource """ - return self._proxy.delete() + return CredentialListContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - @property - def credentials(self): + def __call__(self, sid: str) -> CredentialListContext: """ - Access the credentials + Constructs a CredentialListContext - :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialList - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialList + :param sid: The credential list Sid that uniquely identifies this resource """ - return self._proxy.credentials + return CredentialListContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/sip/credential_list/credential.py b/twilio/rest/api/v2010/account/sip/credential_list/credential.py index 07e1a2e88f..2a237527f2 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,1113 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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") - def __init__(self, version, account_sid, credential_list_sid): + self._solution = { + "account_sid": account_sid, + "credential_list_sid": credential_list_sid, + "sid": sid or self.sid, + } + + self._context: Optional[CredentialContext] = None + + @property + def _proxy(self) -> "CredentialContext": """ - 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 + + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info - :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: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialList - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialList + :returns: ApiResponse with success boolean, status code, and headers """ - super(CredentialList, self).__init__(version) + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, password: Union[str, object] = values.unset + ) -> "CredentialInstance": + """ + Update the CredentialInstance + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The updated CredentialInstance + """ + return self._proxy.update( + password=password, + ) + + async def update_async( + self, password: Union[str, object] = values.unset + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The updated CredentialInstance + """ + return await self._proxy.update_async( + password=password, + ) + + def update_with_http_info( + self, password: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + password=password, + ) + + async def update_with_http_info_async( + self, password: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + password=password, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialContext(InstanceContext): + + def __init__( + self, version: Version, account_sid: str, credential_list_sid: str, sid: str + ): + """ + Initialize the CredentialContext + + :param version: Version that contains the resource + :param account_sid: The unique id of the Account that is responsible for this resource. + :param credential_list_sid: The unique id that identifies the credential list that includes this credential. + :param sid: The unique id that identifies the resource to update. + """ + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, 'credential_list_sid': credential_list_sid, } - self._uri = '/Accounts/{account_sid}/SIP/CredentialLists/{credential_list_sid}/Credentials.json'.format(**self._solution) + self._solution = { + "account_sid": account_sid, + "credential_list_sid": credential_list_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/CredentialLists/{credential_list_sid}/Credentials/{sid}.json".format( + **self._solution + ) - def stream(self, limit=None, page_size=None): + def _delete(self) -> tuple: """ - 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. + Internal helper for delete operation - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance] + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the CredentialInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success - def list(self, limit=None, page_size=None): + def delete_with_http_info(self) -> ApiResponse: """ - Lists CredentialInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the CredentialInstance and return response metadata - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def _delete_async(self) -> tuple: """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + Internal async helper for delete operation - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: Page of CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialPage + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Asynchronous coroutine that deletes the CredentialInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return CredentialPage(self._version, response, self._solution) + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success - def get_page(self, target_url): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Retrieve a specific page of CredentialInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the CredentialInstance and return response metadata - :param str target_url: API-generated URL for the requested results page - :returns: Page of CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialPage + :returns: ApiResponse with success boolean, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) - return CredentialPage(self._version, response, self._solution) + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + - def create(self, username, password): + :returns: The fetched CredentialInstance """ - Create the CredentialInstance + payload, _, _ = self._fetch() + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) - :param unicode username: The username for this credential. - :param unicode password: The password will not be returned in the response. + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance and return response metadata - :returns: The created CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - data = values.of({'Username': username, 'Password': password, }) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + headers = values.of({}) + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + payload, _, _ = await self._fetch_async() 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_with_http_info_async(self) -> ApiResponse: """ - Constructs a CredentialContext + Asynchronous coroutine to fetch the CredentialInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return CredentialContext( + payload, status_code, headers = await self._fetch_async() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __call__(self, sid): + def _update(self, password: Union[str, object] = values.unset) -> tuple: """ - Constructs a CredentialContext + Internal helper for update operation - :param sid: The unique id that identifies the resource to fetch. + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Password": password, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialContext - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialContext + def update(self, password: Union[str, object] = values.unset) -> CredentialInstance: """ - return CredentialContext( + Update the CredentialInstance + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The updated CredentialInstance + """ + payload, _, _ = self._update(password=password) + 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): + def update_with_http_info( + self, password: Union[str, object] = values.unset + ) -> ApiResponse: """ - Provide a friendly representation + Update the CredentialInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return '' + payload, status_code, headers = self._update(password=password) + instance = CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + async def _update_async(self, password: Union[str, object] = values.unset) -> tuple: + """ + Internal async helper for update operation -class CredentialPage(Page): - """ """ + Returns: + tuple: (payload, status_code, headers) + """ - def __init__(self, version, response, solution): + data = values.of( + { + "Password": password, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, password: Union[str, object] = values.unset + ) -> CredentialInstance: """ - Initialize the CredentialPage + Asynchronous coroutine to update the CredentialInstance - :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 + :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.CredentialPage - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialPage + :returns: The updated CredentialInstance """ - super(CredentialPage, self).__init__(version, response) + payload, _, _ = await self._update_async(password=password) + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) - # Path Solution - self._solution = solution + async def update_with_http_info_async( + self, password: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance and return response metadata + + :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_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of CredentialInstance + payload, status_code, headers = await self._update_async(password=password) + instance = CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance + :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, - 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) -> tuple: """ - Fetch the CredentialInstance + Internal helper for create operation - :returns: The fetched CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, username: str, password: str) -> CredentialInstance: + """ + Create the CredentialInstance + + :param username: The username that will be passed when authenticating SIP requests. The username should be sent in response to Twilio's challenge of the initial INVITE. It can be up to 32 characters long. + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The created CredentialInstance + """ + payload, _, _ = self._create(username=username, password=password) 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): + def create_with_http_info(self, username: str, password: str) -> ApiResponse: """ - Update the CredentialInstance + Create the CredentialInstance and return response metadata - :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + username=username, password=password + ) + instance = CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, username: str, password: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, username: str, password: str) -> CredentialInstance: """ - data = values.of({'Password': password, }) + Asynchronously create the CredentialInstance - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :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, _, _ = await self._create_async(username=username, password=password) 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): + async def create_with_http_info_async( + self, username: str, password: str + ) -> ApiResponse: """ - Deletes the CredentialInstance + Asynchronously create the CredentialInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._create_async( + username=username, password=password + ) + instance = CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: """ - Provide a friendly representation + 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: 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 CredentialInstance(InstanceResource): - """ """ + 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) - 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"]) + + return self._version.stream_async(page, limits["limit"]) - :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(CredentialInstance, self).__init__(version) + Streams CredentialInstance and returns headers from first page - # 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'), - } - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'credential_list_sid': credential_list_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: tuple of (generator, status_code, headers) where generator yields instances """ - 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_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: CredentialContext for this CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialContext + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - 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'], + Asynchronously streams CredentialInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode + 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 self._properties['sid'] - @property - def account_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The unique id of the Account that is responsible for this resource. - :rtype: unicode + Lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['account_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialInstance and returns headers from first page - @property - def credential_list_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: ApiResponse with list of instances, status code, and headers """ - :returns: The unique id that identifies the credential list that includes this credential - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['credential_list_sid'] + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately - @property - def username(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 username for this credential. - :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 CredentialPage(self._version, response, solution=self._solution) + + async def 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['username'] + Asynchronously retrieve a single page of CredentialInstance 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 CredentialInstance """ - :returns: The date that this resource was created, given as GMT in RFC 2822 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_created'] + Retrieve a single page with response metadata - @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: ApiResponse with CredentialPage, status code, and headers """ - :returns: The date that this resource was last updated, given as GMT in RFC 2822 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with CredentialPage, status code, and headers """ - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> CredentialPage: """ - return self._properties['uri'] + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page - def fetch(self): + :returns: Page of CredentialInstance """ - Fetch the CredentialInstance + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response, solution=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 - def update(self, password=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance """ - Update the CredentialInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response, solution=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 dd1cb81dcd..3b8f3f32e9 100644 --- a/twilio/rest/api/v2010/account/sip/domain/__init__.py +++ b/twilio/rest/api/v2010/account/sip/domain/__init__.py @@ -1,631 +1,710 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): - """ """ +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") - def __init__(self, version, account_sid): - """ - Initialize the DomainList + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. + self._context: Optional[DomainContext] = None - :returns: twilio.rest.api.v2010.account.sip.domain.DomainList - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainList + @property + def _proxy(self) -> "DomainContext": """ - super(DomainList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/SIP/Domains.json'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def stream(self, limit=None, page_size=None): + :returns: DomainContext for this DomainInstance """ - Streams DomainInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + if self._context is None: + self._context = DomainContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.domain.DomainInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the DomainInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists DomainInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the DomainInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.domain.DomainInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of DomainInstance records from the API. - Request is executed immediately + Deletes the DomainInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with success boolean, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return DomainPage(self._version, response, self._solution) + return self._proxy.delete_with_http_info() - def get_page(self, target_url): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Retrieve a specific page of DomainInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the DomainInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainPage + :returns: ApiResponse with success boolean, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.delete_with_http_info_async() - return DomainPage(self._version, response, self._solution) - - 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): + def fetch(self) -> "DomainInstance": """ - Create the DomainInstance + Fetch 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 - :returns: The created DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance + :returns: The fetched 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, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return DomainInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + return self._proxy.fetch() - def get(self, sid): + async def fetch_async(self) -> "DomainInstance": """ - Constructs a DomainContext + Asynchronous coroutine to fetch the DomainInstance - :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 """ - return DomainContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.fetch_async() - def __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a DomainContext + Fetch the DomainInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return DomainContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.fetch_with_http_info() - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the DomainInstance with HTTP info - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - return '' + return await self._proxy.fetch_with_http_info_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 -class DomainPage(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. - def __init__(self, version, response, solution): + :returns: The updated DomainInstance """ - Initialize the DomainPage + 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, + ) - :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. + 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: twilio.rest.api.v2010.account.sip.domain.DomainPage - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainPage + :returns: The updated DomainInstance """ - super(DomainPage, self).__init__(version, response) + 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, + ) - # Path Solution - self._solution = solution + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the DomainInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_status_callback_method=voice_status_callback_method, + voice_status_callback_url=voice_status_callback_url, + voice_url=voice_url, + sip_registration=sip_registration, + domain_name=domain_name, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) - def get_instance(self, payload): + @property + def auth(self) -> AuthTypesList: """ - Build an instance of DomainInstance + Access the auth + """ + return self._proxy.auth - :param dict payload: Payload response from the API + @property + def credential_list_mappings(self) -> CredentialListMappingList: + """ + Access the credential_list_mappings + """ + return self._proxy.credential_list_mappings - :returns: twilio.rest.api.v2010.account.sip.domain.DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance + @property + def ip_access_control_list_mappings(self) -> IpAccessControlListMappingList: + """ + Access the ip_access_control_list_mappings """ - return DomainInstance(self._version, payload, account_sid=self._solution['account_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 DomainContext(InstanceContext): - """ """ - def __init__(self, version, account_sid, sid): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the DomainContext - :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 + :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(DomainContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/SIP/Domains/{sid}.json'.format(**self._solution) - - # Dependents - self._ip_access_control_list_mappings = None - self._credential_list_mappings = None - self._auth = None + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{sid}.json".format( + **self._solution + ) - def fetch(self): - """ - Fetch the DomainInstance + self._auth: Optional[AuthTypesList] = None + self._credential_list_mappings: Optional[CredentialListMappingList] = None + self._ip_access_control_list_mappings: Optional[ + IpAccessControlListMappingList + ] = None - :returns: The fetched DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance + def _delete(self) -> tuple: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return DomainInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) + Internal helper for delete operation - 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): + Returns: + tuple: (success_boolean, status_code, headers) """ - 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 - :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, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers = values.of({}) - return DomainInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers ) - def delete(self): + def delete(self) -> bool: """ Deletes the DomainInstance + :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + success, _, _ = self._delete() + return success - @property - def ip_access_control_list_mappings(self): + def delete_with_http_info(self) -> ApiResponse: """ - Access the ip_access_control_list_mappings + Deletes the DomainInstance and return response metadata - :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 - """ - 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'], - ) - return self._ip_access_control_list_mappings - @property - def credential_list_mappings(self): + :returns: ApiResponse with success boolean, status code, and headers """ - Access the credential_list_mappings + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :returns: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingList - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingList + async def _delete_async(self) -> tuple: """ - 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'], - ) - return self._credential_list_mappings + Internal async helper for delete operation - @property - def auth(self): + Returns: + tuple: (success_boolean, status_code, headers) """ - 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 - """ - if self._auth is None: - self._auth = AuthTypesList( - self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['sid'], - ) - return self._auth + headers = values.of({}) - def __repr__(self): - """ - Provide a friendly representation + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: Machine friendly representation - :rtype: str + async def delete_async(self) -> bool: """ - 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'), - } + Asynchronous coroutine that deletes the DomainInstance - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): + :returns: True if delete succeeds, False otherwise """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + success, _, _ = await self._delete_async() + return success - :returns: DomainContext for this DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainContext + async def delete_with_http_info_async(self) -> ApiResponse: """ - if self._context is None: - self._context = DomainContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + Asynchronous coroutine that deletes the DomainInstance and return response metadata - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def api_version(self): - """ - :returns: The API version used to process the call - :rtype: unicode + :returns: ApiResponse with success boolean, status code, and headers """ - return self._properties['api_version'] + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - @property - def auth_type(self): - """ - :returns: The types of authentication mapped to the domain - :rtype: unicode + def _fetch(self) -> tuple: """ - return self._properties['auth_type'] + Internal helper for fetch operation - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + Returns: + tuple: (payload, status_code, headers) """ - 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'] + headers = values.of({}) - @property - def domain_name(self): - """ - :returns: The unique address on Twilio to route SIP traffic - :rtype: unicode - """ - return self._properties['domain_name'] + 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'] + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + def fetch(self) -> DomainInstance: """ - return self._properties['sid'] + Fetch the DomainInstance - @property - def uri(self): - """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode - """ - return self._properties['uri'] - @property - def voice_fallback_method(self): - """ - :returns: The HTTP method used with voice_fallback_url - :rtype: unicode + :returns: The fetched DomainInstance """ - return self._properties['voice_fallback_method'] + payload, _, _ = self._fetch() + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - @property - def voice_fallback_url(self): + def fetch_with_http_info(self) -> ApiResponse: """ - :returns: The URL we call when an error occurs while executing TwiML - :rtype: unicode - """ - return self._properties['voice_fallback_url'] + Fetch the DomainInstance and return response metadata - @property - def voice_method(self): - """ - :returns: The HTTP method to use with voice_url - :rtype: unicode - """ - return self._properties['voice_method'] - @property - def voice_status_callback_method(self): - """ - :returns: The HTTP method we use to call voice_status_callback_url - :rtype: unicode + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['voice_status_callback_method'] + payload, status_code, headers = self._fetch() + instance = DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def voice_status_callback_url(self): + async def _fetch_async(self) -> tuple: """ - :returns: The URL that we call with status updates - :rtype: unicode - """ - return self._properties['voice_status_callback_url'] + Internal async helper for fetch operation - @property - def voice_url(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The URL we call when receiving a call - :rtype: unicode - """ - return self._properties['voice_url'] - @property - def subresource_uris(self): - """ - :returns: A list mapping resources associated with the SIP Domain resource - :rtype: unicode - """ - return self._properties['subresource_uris'] + headers = values.of({}) - @property - def sip_registration(self): - """ - :returns: Whether SIP registration is allowed - :rtype: bool - """ - return self._properties['sip_registration'] + headers["Accept"] = "application/json" - @property - def emergency_calling_enabled(self): - """ - :returns: Whether emergency calling is enabled for the domain. - :rtype: bool - """ - return self._properties['emergency_calling_enabled'] + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - @property - def secure(self): + async def fetch_async(self) -> DomainInstance: """ - :returns: Whether secure SIP is enabled for the domain - :rtype: bool - """ - return self._properties['secure'] + Asynchronous coroutine to fetch the DomainInstance - def fetch(self): - """ - Fetch the DomainInstance :returns: The fetched DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance """ - return self._proxy.fetch() + payload, _, _ = await self._fetch_async() + return DomainInstance( + self._version, + payload, + 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): + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 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 """ - return self._proxy.update( + payload, _, _ = self._update( friendly_name=friendly_name, voice_fallback_method=voice_fallback_method, voice_fallback_url=voice_fallback_url, @@ -637,53 +716,1041 @@ def update(self, friendly_name=values.unset, voice_fallback_method=values.unset, domain_name=domain_name, emergency_calling_enabled=emergency_calling_enabled, secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the DomainInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> DomainInstance: + """ + Asynchronous coroutine to update the DomainInstance + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The updated DomainInstance """ - Deletes the DomainInstance + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_status_callback_method=voice_status_callback_method, + voice_status_callback_url=voice_status_callback_url, + voice_url=voice_url, + sip_registration=sip_registration, + domain_name=domain_name, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def auth(self) -> AuthTypesList: """ - return self._proxy.delete() + Access the auth + """ + if self._auth is None: + self._auth = AuthTypesList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._auth @property - def ip_access_control_list_mappings(self): + def credential_list_mappings(self) -> CredentialListMappingList: + """ + Access the credential_list_mappings + """ + if self._credential_list_mappings is None: + self._credential_list_mappings = CredentialListMappingList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._credential_list_mappings + + @property + def ip_access_control_list_mappings(self) -> IpAccessControlListMappingList: """ Access the ip_access_control_list_mappings + """ + if self._ip_access_control_list_mappings is None: + self._ip_access_control_list_mappings = IpAccessControlListMappingList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._ip_access_control_list_mappings - :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 __repr__(self) -> str: """ - return self._proxy.ip_access_control_list_mappings + Provide a friendly representation - @property - def credential_list_mappings(self): + :returns: Machine friendly representation """ - Access the credential_list_mappings + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DomainPage(Page): - :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 get_instance(self, payload: Dict[str, Any]) -> DomainInstance: """ - return self._proxy.credential_list_mappings + Build an instance of DomainInstance - @property - def auth(self): + :param payload: Payload response from the API """ - 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 + return DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: """ - return self._proxy.auth + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DomainList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the DomainList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the SipDomain resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains.json".format(**self._solution) + + def _create( + self, + domain_name: str, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + domain_name: str, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> DomainInstance: + """ + Create the DomainInstance + + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_url: The URL we should when the domain receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The created DomainInstance + """ + payload, _, _ = self._create( + domain_name=domain_name, + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + voice_status_callback_url=voice_status_callback_url, + voice_status_callback_method=voice_status_callback_method, + sip_registration=sip_registration, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + return DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the DomainInstance and return response metadata + + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_url: The URL we should when the domain receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + domain_name=domain_name, + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + voice_status_callback_url=voice_status_callback_url, + voice_status_callback_method=voice_status_callback_method, + sip_registration=sip_registration, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + instance = DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + domain_name: str, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> DomainInstance: + """ + Asynchronously create the DomainInstance + + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_url: The URL we should when the domain receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The created DomainInstance + """ + payload, _, _ = await self._create_async( + domain_name=domain_name, + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + voice_status_callback_url=voice_status_callback_url, + voice_status_callback_method=voice_status_callback_method, + sip_registration=sip_registration, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + return DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the DomainInstance and return response metadata + + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_url: The URL we should when the domain receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + domain_name=domain_name, + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + voice_status_callback_url=voice_status_callback_url, + voice_status_callback_method=voice_status_callback_method, + sip_registration=sip_registration, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + instance = DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DomainInstance]: + """ + Streams DomainInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DomainInstance]: + """ + Asynchronously streams DomainInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DomainInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DomainInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DomainInstance]: + """ + Lists DomainInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DomainInstance]: + """ + Asynchronously lists DomainInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DomainInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DomainInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DomainPage: + """ + Retrieve a single page of DomainInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DomainInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DomainPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DomainPage: + """ + Asynchronously retrieve a single page of DomainInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DomainInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DomainPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DomainPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DomainPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DomainPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DomainPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> DomainPage: + """ + Retrieve a specific page of DomainInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DomainInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DomainPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> DomainPage: + """ + Asynchronously retrieve a specific page of DomainInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DomainInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DomainPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> DomainContext: + """ + Constructs a DomainContext + + :param sid: The Twilio-provided string that uniquely identifies the SipDomain resource to update. + """ + return DomainContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> DomainContext: + """ + Constructs a DomainContext + + :param sid: The Twilio-provided string that uniquely identifies the SipDomain resource to update. + """ + return DomainContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 3f43e8016d..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'], limits['page_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 460741df79..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'], limits['page_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 b24bc7d64b..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'], limits['page_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..0e539d09c6 --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py @@ -0,0 +1,949 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthCallsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthCallsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthCallsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthCallsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the AuthCallsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthCallsCredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthCallsCredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthCallsCredentialListMappingInstance: + """ + Fetch the AuthCallsCredentialListMappingInstance + + + :returns: The fetched AuthCallsCredentialListMappingInstance + """ + payload, _, _ = self._fetch() + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthCallsCredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AuthCallsCredentialListMappingInstance: + """ + Asynchronous coroutine to fetch the AuthCallsCredentialListMappingInstance + + + :returns: The fetched AuthCallsCredentialListMappingInstance + """ + payload, _, _ = await self._fetch_async() + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthCallsCredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(credential_list_sid=credential_list_sid) + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def create_with_http_info(self, credential_list_sid: str) -> ApiResponse: + """ + Create the AuthCallsCredentialListMappingInstance and return response metadata + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + credential_list_sid=credential_list_sid + ) + instance = AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, credential_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + credential_list_sid=credential_list_sid + ) + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + async def create_with_http_info_async( + self, credential_list_sid: str + ) -> ApiResponse: + """ + Asynchronously create the AuthCallsCredentialListMappingInstance and return response metadata + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + credential_list_sid=credential_list_sid + ) + instance = AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AuthCallsCredentialListMappingInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AuthCallsCredentialListMappingInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AuthCallsCredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AuthCallsCredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution + ) + + async def 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, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthCallsCredentialListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AuthCallsCredentialListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthCallsCredentialListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AuthCallsCredentialListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..d8a7aba9a7 --- /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,955 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthCallsIpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthCallsIpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthCallsIpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthCallsIpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the AuthCallsIpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthCallsIpAccessControlListMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthCallsIpAccessControlListMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthCallsIpAccessControlListMappingInstance: + """ + Fetch the AuthCallsIpAccessControlListMappingInstance + + + :returns: The fetched AuthCallsIpAccessControlListMappingInstance + """ + payload, _, _ = self._fetch() + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthCallsIpAccessControlListMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AuthCallsIpAccessControlListMappingInstance: + """ + Asynchronous coroutine to fetch the AuthCallsIpAccessControlListMappingInstance + + + :returns: The fetched AuthCallsIpAccessControlListMappingInstance + """ + payload, _, _ = await self._fetch_async() + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthCallsIpAccessControlListMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def create_with_http_info(self, ip_access_control_list_sid: str) -> ApiResponse: + """ + Create the AuthCallsIpAccessControlListMappingInstance and return response metadata + + :param ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, ip_access_control_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + ip_access_control_list_sid=ip_access_control_list_sid + ) + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + async def create_with_http_info_async( + self, ip_access_control_list_sid: str + ) -> ApiResponse: + """ + Asynchronously create the AuthCallsIpAccessControlListMappingInstance and return response metadata + + :param ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AuthCallsIpAccessControlListMappingInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AuthCallsIpAccessControlListMappingInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AuthCallsIpAccessControlListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AuthCallsIpAccessControlListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution + ) + + async def 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, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthCallsIpAccessControlListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AuthCallsIpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthCallsIpAccessControlListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AuthCallsIpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..78671458dc --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py @@ -0,0 +1,949 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthRegistrationsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthRegistrationsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthRegistrationsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthRegistrationsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the AuthRegistrationsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthRegistrationsCredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthRegistrationsCredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthRegistrationsCredentialListMappingInstance: + """ + Fetch the AuthRegistrationsCredentialListMappingInstance + + + :returns: The fetched AuthRegistrationsCredentialListMappingInstance + """ + payload, _, _ = self._fetch() + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthRegistrationsCredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AuthRegistrationsCredentialListMappingInstance: + """ + Asynchronous coroutine to fetch the AuthRegistrationsCredentialListMappingInstance + + + :returns: The fetched AuthRegistrationsCredentialListMappingInstance + """ + payload, _, _ = await self._fetch_async() + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthRegistrationsCredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(credential_list_sid=credential_list_sid) + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def create_with_http_info(self, credential_list_sid: str) -> ApiResponse: + """ + Create the AuthRegistrationsCredentialListMappingInstance and return response metadata + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + credential_list_sid=credential_list_sid + ) + instance = AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, credential_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + credential_list_sid=credential_list_sid + ) + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + async def create_with_http_info_async( + self, credential_list_sid: str + ) -> ApiResponse: + """ + Asynchronously create the AuthRegistrationsCredentialListMappingInstance and return response metadata + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + credential_list_sid=credential_list_sid + ) + instance = AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AuthRegistrationsCredentialListMappingInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AuthRegistrationsCredentialListMappingInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AuthRegistrationsCredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AuthRegistrationsCredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution + ) + + async def 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, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthRegistrationsCredentialListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AuthRegistrationsCredentialListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthRegistrationsCredentialListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AuthRegistrationsCredentialListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 be1a2c799c..cbdbc3e470 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,943 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialListMappingInstance - :param unicode credential_list_sid: A string that identifies the CredentialList resource to map to the SIP domain - :returns: The created CredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'CredentialListSid': credential_list_sid, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialListMappingInstance with HTTP info - return CredentialListMappingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListMappingInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "CredentialListMappingInstance": + """ + Fetch the CredentialListMappingInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched CredentialListMappingInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the CredentialListMappingInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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 """ - 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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of CredentialListMappingInstance records from the API. - Request is executed immediately + Fetch the CredentialListMappingInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialListMappingInstance with HTTP info - return CredentialListMappingPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of CredentialListMappingInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of CredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingPage + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialListMappingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Initialize the CredentialListMappingContext + + :param version: Version that contains the resource + :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. + :param domain_sid: A 34 character string that uniquely identifies the SIP Domain that includes the resource to fetch. + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/CredentialListMappings/{sid}.json".format( + **self._solution ) - return CredentialListMappingPage(self._version, response, self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation - def get(self, sid): + Returns: + tuple: (success_boolean, status_code, headers) """ - Constructs a CredentialListMappingContext - :param sid: A string that identifies the resource to fetch + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the CredentialListMappingInstance + - :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( + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialListMappingInstance: + """ + Fetch the CredentialListMappingInstance + + + :returns: The fetched CredentialListMappingInstance + """ + payload, _, _ = self._fetch() + 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 __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a CredentialListMappingContext + Fetch the CredentialListMappingInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return CredentialListMappingContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class CredentialListMappingPage(Page): - """ """ + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + async def fetch_async(self) -> CredentialListMappingInstance: """ - Initialize the CredentialListMappingPage + Asynchronous coroutine to fetch the CredentialListMappingInstance - :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 - :returns: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingPage - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingPage + :returns: The fetched CredentialListMappingInstance """ - super(CredentialListMappingPage, self).__init__(version, response) + payload, _, _ = await self._fetch_async() + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialListMappingInstance and return response metadata - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of CredentialListMappingInstance + payload, status_code, headers = await self._fetch_async() + instance = CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation - :param dict payload: Payload response from the API + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialListMappingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialListMappingInstance: + """ + Build an instance of CredentialListMappingInstance - :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) -> tuple: """ - Fetch the CredentialListMappingInstance + Internal helper for create operation - :returns: The fetched CredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingInstance + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, credential_list_sid: str) -> CredentialListMappingInstance: + """ + Create the CredentialListMappingInstance + + :param credential_list_sid: A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. + + :returns: The created CredentialListMappingInstance + """ + payload, _, _ = self._create(credential_list_sid=credential_list_sid) + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def create_with_http_info(self, credential_list_sid: str) -> ApiResponse: + """ + Create the CredentialListMappingInstance and return response metadata + + :param credential_list_sid: A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. + + :returns: ApiResponse with instance, status code, and headers """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, status_code, headers = self._create( + credential_list_sid=credential_list_sid + ) + instance = CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, credential_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, credential_list_sid: str + ) -> CredentialListMappingInstance: + """ + Asynchronously create the CredentialListMappingInstance + + :param credential_list_sid: A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. + + :returns: The created CredentialListMappingInstance + """ + payload, _, _ = await self._create_async( + credential_list_sid=credential_list_sid + ) 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_with_http_info_async( + self, credential_list_sid: str + ) -> ApiResponse: """ - Deletes the CredentialListMappingInstance + Asynchronously create the CredentialListMappingInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param credential_list_sid: A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._create_async( + credential_list_sid=credential_list_sid + ) + instance = CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialListMappingInstance]: """ - Provide a friendly representation + 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. - :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 CredentialListMappingInstance(InstanceResource): - """ """ + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialListMappingInstance]: + """ + Asynchronously streams CredentialListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def __init__(self, version, payload, account_sid, domain_sid, sid=None): + :returns: Generator that will yield up to limit results """ - Initialize the CredentialListMappingInstance + limits = self._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.domain.credential_list_mapping.CredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingInstance + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(CredentialListMappingInstance, self).__init__(version) + Streams CredentialListMappingInstance and returns headers from first page - # 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'), - } - # 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: tuple of (generator, status_code, headers) where generator yields instances """ - 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_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: CredentialListMappingContext for this CredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingContext + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - 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'], + Asynchronously streams CredentialListMappingInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListMappingInstance]: + """ + Lists CredentialListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def account_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListMappingInstance]: """ - :returns: The unique id of the Account that is responsible for this resource. - :rtype: unicode + 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['account_sid'] - @property - def date_created(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The date that this resource was created, given as GMT in RFC 2822 format. - :rtype: datetime + Lists CredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_created'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def date_updated(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The date that this resource was last updated, given as GMT in RFC 2822 format. - :rtype: datetime + Asynchronously lists CredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_updated'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, solution=self._solution + ) + + async def 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, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The URI for this resource, relative to https://api.twilio.com - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialListMappingPage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The credentials associated with this resource. - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialListMappingPage, status code, and headers """ - return self._properties['subresource_uris'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - def fetch(self): + def get_page(self, target_url: str) -> CredentialListMappingPage: """ - Fetch the CredentialListMappingInstance + Retrieve a specific page of CredentialListMappingInstance records from the API. + Request is executed immediately - :returns: The fetched CredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialListMappingInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return CredentialListMappingPage( + self._version, response, solution=self._solution + ) - def delete(self): + async def get_page_async(self, target_url: str) -> CredentialListMappingPage: """ - Deletes the CredentialListMappingInstance + Asynchronously retrieve a specific page of CredentialListMappingInstance 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 CredentialListMappingInstance """ - return self._proxy.delete() + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialListMappingPage( + self._version, response, solution=self._solution + ) + + def get(self, sid: str) -> CredentialListMappingContext: + """ + Constructs a CredentialListMappingContext + + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + return CredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> CredentialListMappingContext: + """ + Constructs a CredentialListMappingContext + + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + return CredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 a82eaf3aa4..2a3c582b70 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,951 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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") - 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[IpAccessControlListMappingContext] = None + + @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 + return self._proxy.delete() - :param unicode ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAccessControlListMappingInstance - :returns: The created IpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({'IpAccessControlListSid': ip_access_control_list_sid, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAccessControlListMappingInstance with HTTP info - return IpAccessControlListMappingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListMappingInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "IpAccessControlListMappingInstance": + """ + Fetch the IpAccessControlListMappingInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched IpAccessControlListMappingInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the IpAccessControlListMappingInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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 """ - 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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of IpAccessControlListMappingInstance records from the API. - Request is executed immediately + Fetch the IpAccessControlListMappingInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAccessControlListMappingInstance with HTTP info - return IpAccessControlListMappingPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of IpAccessControlListMappingInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of IpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingPage + :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 IpAccessControlListMappingPage(self._version, response, self._solution) - def get(self, sid): +class IpAccessControlListMappingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): """ - Constructs a IpAccessControlListMappingContext + Initialize the IpAccessControlListMappingContext + :param version: Version that contains the resource + :param account_sid: The unique id of the Account that is responsible for this resource. + :param domain_sid: A 34 character string that uniquely identifies the SIP domain. :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/IpAccessControlListMappings/{sid}.json".format( + **self._solution + ) - :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 + def _delete(self) -> tuple: """ - return IpAccessControlListMappingContext( + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the IpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAccessControlListMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAccessControlListMappingInstance: + """ + Fetch the IpAccessControlListMappingInstance + + + :returns: The fetched IpAccessControlListMappingInstance + """ + payload, _, _ = self._fetch() + 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 __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a IpAccessControlListMappingContext + Fetch the IpAccessControlListMappingInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return IpAccessControlListMappingContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class IpAccessControlListMappingPage(Page): - """ """ + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + async def fetch_async(self) -> IpAccessControlListMappingInstance: """ - Initialize the IpAccessControlListMappingPage + Asynchronous coroutine to fetch the IpAccessControlListMappingInstance - :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 - :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 + :returns: The fetched IpAccessControlListMappingInstance + """ + payload, _, _ = await self._fetch_async() + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: """ - super(IpAccessControlListMappingPage, self).__init__(version, response) + Asynchronous coroutine to fetch the IpAccessControlListMappingInstance and return response metadata - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of IpAccessControlListMappingInstance + payload, status_code, headers = await self._fetch_async() + instance = IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 IpAccessControlListMappingPage(Page): - :param dict payload: Payload response from the API + def get_instance( + self, payload: Dict[str, Any] + ) -> IpAccessControlListMappingInstance: + """ + Build an instance of IpAccessControlListMappingInstance - :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) -> tuple: """ - Fetch the IpAccessControlListMappingInstance + Internal helper for create operation - :returns: The fetched IpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, ip_access_control_list_sid: str + ) -> IpAccessControlListMappingInstance: + """ + Create the IpAccessControlListMappingInstance + + :param ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. + + :returns: The created IpAccessControlListMappingInstance + """ + payload, _, _ = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) 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): + def create_with_http_info(self, ip_access_control_list_sid: str) -> ApiResponse: """ - Deletes the IpAccessControlListMappingInstance + Create the IpAccessControlListMappingInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _create_async(self, ip_access_control_list_sid: str) -> tuple: """ - Provide a friendly representation + Internal async helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - 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"}) -class IpAccessControlListMappingInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - def __init__(self, version, payload, account_sid, domain_sid, sid=None): + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, ip_access_control_list_sid: str + ) -> IpAccessControlListMappingInstance: """ - Initialize the IpAccessControlListMappingInstance + Asynchronously create the IpAccessControlListMappingInstance + + :param ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. + + :returns: The created IpAccessControlListMappingInstance + """ + payload, _, _ = await self._create_async( + ip_access_control_list_sid=ip_access_control_list_sid + ) + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) - :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 + async def create_with_http_info_async( + self, ip_access_control_list_sid: str + ) -> ApiResponse: """ - super(IpAccessControlListMappingInstance, self).__init__(version) + Asynchronously create the IpAccessControlListMappingInstance and return response metadata - # 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 ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'domain_sid': domain_sid, - 'sid': sid or self._properties['sid'], - } + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpAccessControlListMappingInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: IpAccessControlListMappingContext for this IpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingContext + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = IpAccessControlListMappingContext( - self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - sid=self._solution['sid'], + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAccessControlListMappingInstance]: + """ + Asynchronously streams IpAccessControlListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams IpAccessControlListMappingInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams IpAccessControlListMappingInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListMappingInstance]: + """ + Lists IpAccessControlListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def account_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListMappingInstance]: """ - :returns: The unique id of the Account that is responsible for this resource. - :rtype: unicode + 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['account_sid'] - @property - def date_created(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The date that this resource was created, given as GMT in RFC 2822 format. - :rtype: datetime + Lists IpAccessControlListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_created'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def date_updated(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The date that this resource was last updated, given as GMT in RFC 2822 format. - :rtype: datetime + Asynchronously lists IpAccessControlListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_updated'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, solution=self._solution + ) + + async def 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, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The URI for this resource, relative to https://api.twilio.com - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpAccessControlListMappingPage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The list of IP addresses associated with this domain. - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpAccessControlListMappingPage, status code, and headers """ - return self._properties['subresource_uris'] + data = values.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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> IpAccessControlListMappingPage: """ - Fetch the IpAccessControlListMappingInstance + Retrieve a specific page of IpAccessControlListMappingInstance records from the API. + Request is executed immediately - :returns: The fetched IpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAccessControlListMappingInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return IpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) - def delete(self): + async def get_page_async(self, target_url: str) -> IpAccessControlListMappingPage: """ - Deletes the IpAccessControlListMappingInstance + Asynchronously retrieve a specific page of IpAccessControlListMappingInstance 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 IpAccessControlListMappingInstance """ - return self._proxy.delete() + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) + + def get(self, sid: str) -> IpAccessControlListMappingContext: + """ + Constructs a IpAccessControlListMappingContext + + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + return IpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> IpAccessControlListMappingContext: + """ + Constructs a IpAccessControlListMappingContext + + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + return IpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 6d083fecd3..e2161d40ae 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,1082 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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") - def __init__(self, version, account_sid): + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + + self._context: Optional[IpAccessControlListContext] = None + + @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. + 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 IpAccessControlListInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance] + + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAccessControlListInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists IpAccessControlListInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "IpAccessControlListInstance": """ - Retrieve a single page of IpAccessControlListInstance records from the API. - Request is executed immediately + Fetch the IpAccessControlListInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListPage + :returns: The fetched IpAccessControlListInstance """ - 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) -> "IpAccessControlListInstance": + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance - return IpAccessControlListPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched IpAccessControlListInstance """ - Retrieve a specific page of IpAccessControlListInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAccessControlListInstance with HTTP info - :returns: Page of IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() - return IpAccessControlListPage(self._version, response, self._solution) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance with HTTP info - def create(self, friendly_name): + + :returns: ApiResponse with instance, status code, and headers """ - Create the IpAccessControlListInstance + return await self._proxy.fetch_with_http_info_async() - :param unicode friendly_name: A human readable description of this resource + def update(self, friendly_name: str) -> "IpAccessControlListInstance": + """ + Update the IpAccessControlListInstance - :returns: The created IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: The updated IpAccessControlListInstance """ - data = values.of({'FriendlyName': friendly_name, }) + return self._proxy.update( + friendly_name=friendly_name, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def update_async(self, friendly_name: str) -> "IpAccessControlListInstance": + """ + Asynchronous coroutine to update the IpAccessControlListInstance - return IpAccessControlListInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: The updated IpAccessControlListInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, ) - def get(self, sid): + def update_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Constructs a IpAccessControlListContext + Update the IpAccessControlListInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return IpAccessControlListContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: """ - Constructs a IpAccessControlListContext + Asynchronous coroutine to update the IpAccessControlListInstance with HTTP info - :param sid: A string that identifies the resource to fetch + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext + @property + def ip_addresses(self) -> IpAddressList: + """ + Access the ip_addresses """ - return IpAccessControlListContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.ip_addresses - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class IpAccessControlListPage(Page): - """ """ +class IpAccessControlListContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the IpAccessControlListPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. + Initialize the IpAccessControlListContext - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListPage - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListPage + :param version: Version that contains the resource + :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. + :param sid: A 34 character string that uniquely identifies the resource to udpate. """ - super(IpAccessControlListPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/SIP/IpAccessControlLists/{sid}.json".format( + **self._solution + ) + ) + + self._ip_addresses: Optional[IpAddressList] = None - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of IpAccessControlListInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", 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 + def delete(self) -> bool: """ - return IpAccessControlListInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], + Deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAccessControlListInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the IpAccessControlListInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance and return response metadata -class IpAccessControlListContext(InstanceContext): - """ """ - def __init__(self, version, account_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the IpAccessControlListContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :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: + tuple: (payload, status_code, headers) """ - super(IpAccessControlListContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/SIP/IpAccessControlLists/{sid}.json'.format(**self._solution) + headers = values.of({}) - # Dependents - self._ip_addresses = None + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAccessControlListInstance: """ Fetch the IpAccessControlListInstance + :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._fetch() + return IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAccessControlListInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> IpAccessControlListInstance: + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + payload, _, _ = await self._fetch_async() 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 fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, friendly_name: str) -> IpAccessControlListInstance: """ Update the IpAccessControlListInstance - :param unicode friendly_name: A human readable description of this resource + :param friendly_name: A human readable descriptive text, up to 255 characters long. :returns: The updated IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance """ - data = values.of({'FriendlyName': friendly_name, }) + payload, _, _ = self._update(friendly_name=friendly_name) + return IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Update the IpAccessControlListInstance and return response metadata + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for update operation - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async(self, friendly_name: str) -> IpAccessControlListInstance: + """ + Asynchronous coroutine to update the IpAccessControlListInstance + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: The updated IpAccessControlListInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) return IpAccessControlListInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: """ - Deletes the IpAccessControlListInstance + Asynchronous coroutine to update the IpAccessControlListInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 + + :param payload: Payload response from the API + """ + + return IpAccessControlListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" - def __init__(self, version, payload, account_sid, sid=None): + +class IpAccessControlListList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - Initialize the IpAccessControlListInstance + 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: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance """ - super(IpAccessControlListInstance, 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.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'), + # Path Solution + self._solution = { + "account_sid": account_sid, } + self._uri = "/Accounts/{account_sid}/SIP/IpAccessControlLists.json".format( + **self._solution + ) - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + def _create(self, friendly_name: str) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: IpAccessControlListContext for this IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, friendly_name: str) -> IpAccessControlListInstance: """ - if self._context is None: - self._context = IpAccessControlListContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + Create the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. + + :returns: The created IpAccessControlListInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) + return IpAccessControlListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def create_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Create the IpAccessControlListInstance and return response metadata + + :param friendly_name: A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = IpAccessControlListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, friendly_name: str) -> IpAccessControlListInstance: + """ + Asynchronously create the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. + + :returns: The created IpAccessControlListInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return IpAccessControlListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronously create the IpAccessControlListInstance and return response metadata + + :param friendly_name: A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = IpAccessControlListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpAccessControlListInstance]: + """ + Streams IpAccessControlListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAccessControlListInstance]: + """ + Asynchronously streams IpAccessControlListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams IpAccessControlListInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams IpAccessControlListInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: + """ + Lists IpAccessControlListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: """ - :returns: A string that uniquely identifies this resource - :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['sid'] - @property - def account_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The unique sid that identifies this account - :rtype: unicode + Lists IpAccessControlListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['account_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def friendly_name(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: A human readable description of this resource - :rtype: unicode + Asynchronously lists IpAccessControlListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['friendly_name'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> IpAccessControlListPage: """ - :returns: The date this resource was created - :rtype: datetime + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAccessControlListPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAccessControlListPage: """ - :returns: The date this resource was last updated - :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_updated'] + 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 IpAccessControlListPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The IP addresses associated with this resource. - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpAccessControlListPage, status code, and headers """ - return self._properties['subresource_uris'] + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IpAccessControlListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The URI for this resource - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpAccessControlListPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IpAccessControlListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 e30bda1369..aefcad2b39 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,1253 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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") - def __init__(self, version, account_sid, ip_access_control_list_sid): + self._solution = { + "account_sid": account_sid, + "ip_access_control_list_sid": ip_access_control_list_sid, + "sid": sid or self.sid, + } + + self._context: Optional[IpAddressContext] = None + + @property + def _proxy(self) -> "IpAddressContext": """ - 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 + + :returns: IpAddressContext for this IpAddressInstance + """ + if self._context is None: + self._context = IpAddressContext( + self._version, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the IpAddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAddressInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAddressInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "IpAddressInstance": + """ + Fetch the IpAddressInstance + + + :returns: The fetched IpAddressInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IpAddressInstance": + """ + Asynchronous coroutine to fetch the IpAddressInstance + + + :returns: The fetched IpAddressInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAddressInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAddressInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> "IpAddressInstance": + """ + Update the IpAddressInstance + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The updated IpAddressInstance + """ + return self._proxy.update( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + + async def update_async( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> "IpAddressInstance": + """ + Asynchronous coroutine to update the IpAddressInstance + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The updated IpAddressInstance + """ + return await self._proxy.update_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + + def update_with_http_info( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the IpAddressInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + + async def update_with_http_info_async( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IpAddressInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation - :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: 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, + ): + """ + Initialize the IpAddressContext - :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 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(IpAddressList, self).__init__(version) + super().__init__(version) # Path Solution self._solution = { - 'account_sid': account_sid, - 'ip_access_control_list_sid': ip_access_control_list_sid, + "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.json'.format(**self._solution) + self._uri = "/Accounts/{account_sid}/SIP/IpAccessControlLists/{ip_access_control_list_sid}/IpAddresses/{sid}.json".format( + **self._solution + ) - def stream(self, limit=None, page_size=None): + def _delete(self) -> tuple: """ - 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. + Internal helper for delete operation - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance] + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the IpAddressInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success - def list(self, limit=None, page_size=None): + def delete_with_http_info(self) -> ApiResponse: """ - Lists IpAddressInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the IpAddressInstance and return response metadata - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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.ip_address.IpAddressInstance] + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def _delete_async(self) -> tuple: """ - Retrieve a single page of IpAddressInstance records from the API. - Request is executed immediately + Internal async helper for delete operation - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: Page of IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressPage + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Asynchronous coroutine that deletes the IpAddressInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return IpAddressPage(self._version, response, self._solution) + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success - def get_page(self, target_url): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Retrieve a specific page of IpAddressInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the IpAddressInstance and return response metadata - :param str target_url: API-generated URL for the requested results page - :returns: Page of IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressPage + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) - return IpAddressPage(self._version, response, self._solution) + def fetch(self) -> IpAddressInstance: + """ + Fetch the IpAddressInstance - def create(self, friendly_name, ip_address, cidr_prefix_length=values.unset): + + :returns: The fetched IpAddressInstance """ - Create the IpAddressInstance + payload, _, _ = self._fetch() + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) - :param 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. + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAddressInstance and return response metadata - :returns: The created IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance + + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'FriendlyName': friendly_name, - 'IpAddress': ip_address, - 'CidrPrefixLength': cidr_prefix_length, - }) + payload, status_code, headers = self._fetch() + instance = 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"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + headers["Accept"] = "application/json" + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> IpAddressInstance: + """ + Asynchronous coroutine to fetch the IpAddressInstance + + + :returns: The fetched IpAddressInstance + """ + payload, _, _ = await self._fetch_async() 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_with_http_info_async(self) -> ApiResponse: """ - Constructs a IpAddressContext + Asynchronous coroutine to fetch the IpAddressInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return IpAddressContext( + payload, status_code, headers = await self._fetch_async() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - Constructs a IpAddressContext - :param sid: A string that identifies the IpAddress resource to fetch + data = values.of( + { + "IpAddress": ip_address, + "FriendlyName": friendly_name, + "CidrPrefixLength": cidr_prefix_length, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - :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 + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return IpAddressContext( + Update the IpAddressInstance + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The updated IpAddressInstance + """ + payload, _, _ = self._update( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + 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): + def update_with_http_info( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Provide a friendly representation + Update the IpAddressInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return '' + payload, status_code, headers = self._update( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + instance = 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"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + 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, + ) -> tuple: + """ + Internal async helper for update operation -class IpAddressPage(Page): - """ """ + Returns: + tuple: (payload, status_code, headers) + """ + + 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" - def __init__(self, version, response, solution): + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - Initialize the IpAddressPage + Asynchronous coroutine to update the IpAddressInstance - :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. + :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.IpAddressPage - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressPage + :returns: The updated IpAddressInstance """ - super(IpAddressPage, self).__init__(version, response) + payload, _, _ = await self._update_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + 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"], + ) - # Path Solution - self._solution = solution + async def update_with_http_info_async( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IpAddressInstance and return response metadata + + :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_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of IpAddressInstance + payload, status_code, headers = await self._update_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + instance = 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"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + def __repr__(self) -> str: + """ + Provide a friendly representation - :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 + :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: Dict[str, Any]) -> IpAddressInstance: + """ + Build an instance of IpAddressInstance + + :param payload: Payload response from the API + """ + return IpAddressInstance( self._version, payload, - account_sid=self._solution['account_sid'], - ip_access_control_list_sid=self._solution['ip_access_control_list_sid'], + 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, + ) -> tuple: """ - Fetch the IpAddressInstance + Internal helper for create operation - :returns: The fetched IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Create the IpAddressInstance + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The created IpAddressInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + ip_address=ip_address, + cidr_prefix_length=cidr_prefix_length, + ) 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): + def create_with_http_info( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Update the IpAddressInstance + Create the IpAddressInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'IpAddress': ip_address, - 'FriendlyName': friendly_name, - 'CidrPrefixLength': cidr_prefix_length, - }) + payload, status_code, headers = self._create( + friendly_name=friendly_name, + ip_address=ip_address, + cidr_prefix_length=cidr_prefix_length, + ) + instance = IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "IpAddress": ip_address, + "CidrPrefixLength": cidr_prefix_length, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: + """ + Asynchronously create the IpAddressInstance + + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The created IpAddressInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + ip_address=ip_address, + cidr_prefix_length=cidr_prefix_length, + ) 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): + async def create_with_http_info_async( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the IpAddressInstance + Asynchronously create the IpAddressInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + ip_address=ip_address, + cidr_prefix_length=cidr_prefix_length, + ) + instance = IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpAddressInstance]: """ - Provide a friendly representation + 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: 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 IpAddressInstance(InstanceResource): - """ """ + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAddressInstance]: + """ + Asynchronously streams IpAddressInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def __init__(self, version, payload, account_sid, ip_access_control_list_sid, - sid=None): + :returns: Generator that will yield up to limit results """ - Initialize the IpAddressInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(IpAddressInstance, self).__init__(version) + Streams IpAddressInstance and returns headers from first page - # 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'), - } - # 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'], - } + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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: tuple of (generator, status_code, headers) where generator yields instances """ - 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_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: IpAddressContext for this IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressContext + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - 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 + Asynchronously streams IpAddressInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAddressInstance]: """ - return self._properties['sid'] + Lists IpAddressInstance 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 limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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 id of the Account that is responsible for this resource. - :rtype: unicode + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAddressInstance]: """ - return self._properties['account_sid'] + 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. - @property - def friendly_name(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: A human readable descriptive text for this resource, up to 64 characters long. - :rtype: unicode + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['friendly_name'] + Lists IpAddressInstance and returns headers from first page - @property - def ip_address(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: ApiResponse with list of instances, status code, and headers """ - :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 + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['ip_address'] + Asynchronously lists IpAddressInstance and returns headers from first page - @property - def cidr_prefix_length(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: ApiResponse with list of instances, status code, and headers """ - :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 + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['cidr_prefix_length'] + Retrieve a single page of IpAddressInstance records from the API. + Request is executed immediately - @property - def ip_access_control_list_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 IpAddressInstance """ - :returns: The unique id of the IpAccessControlList resource that includes this resource. - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAddressPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAddressPage: """ - return self._properties['ip_access_control_list_sid'] + Asynchronously retrieve a single page of IpAddressInstance 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 IpAddressInstance """ - :returns: The date that this resource was created, given as GMT in RFC 2822 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAddressPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_created'] + Retrieve a single page with response metadata - @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: ApiResponse with IpAddressPage, status code, and headers """ - :returns: The date that this resource was last updated, given as GMT in RFC 2822 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IpAddressPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with IpAddressPage, status code, and headers """ - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IpAddressPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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 - def update(self, ip_address=values.unset, friendly_name=values.unset, - cidr_prefix_length=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAddressInstance """ - Update the IpAddressInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpAddressPage(self._version, response, solution=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..4cc10f7026 100644 --- a/twilio/rest/api/v2010/account/token.py +++ b/twilio/rest/api/v2010/account/token.py @@ -1,190 +1,195 @@ -# 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 +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + 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 TokenList(ListResource): - """ """ +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 __init__(self, version, account_sid): + def __repr__(self) -> str: """ - Initialize the TokenList - - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.token.TokenList - :rtype: twilio.rest.api.v2010.account.token.TokenList + :returns: Machine friendly representation """ - super(TokenList, self).__init__(version) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Tokens.json'.format(**self._solution) - def create(self, ttl=values.unset): +class TokenList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - Create the TokenInstance + Initialize the TokenList - :param unicode ttl: The duration in seconds the credentials are valid + :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: The created TokenInstance - :rtype: twilio.rest.api.v2010.account.token.TokenInstance """ - data = values.of({'Ttl': ttl, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + super().__init__(version) - return TokenInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Tokens.json".format(**self._solution) - def __repr__(self): + def _create(self, ttl: Union[int, object] = values.unset) -> tuple: """ - Provide a friendly representation + Internal helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class TokenPage(Page): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, response, solution): - """ - Initialize the TokenPage + headers["Accept"] = "application/json" - :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 + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.api.v2010.account.token.TokenPage - :rtype: twilio.rest.api.v2010.account.token.TokenPage + def create(self, ttl: Union[int, object] = values.unset) -> TokenInstance: """ - super(TokenPage, self).__init__(version, response) + Create the TokenInstance - # Path Solution - self._solution = solution + :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). - def get_instance(self, payload): + :returns: The created TokenInstance """ - Build an instance of TokenInstance - - :param dict payload: Payload response from the API + payload, _, _ = self._create(ttl=ttl) + 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 + def create_with_http_info( + self, ttl: Union[int, object] = values.unset + ) -> ApiResponse: """ - return TokenInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Create the TokenInstance and return response metadata - def __repr__(self): - """ - Provide a friendly representation + :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). - :returns: Machine friendly representation - :rtype: str + :returns: ApiResponse with instance, status code, and headers """ - return '' + payload, status_code, headers = self._create(ttl=ttl) + instance = TokenInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - -class TokenInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid): + async def _create_async(self, ttl: Union[int, object] = values.unset) -> tuple: """ - Initialize the TokenInstance + Internal async helper for create operation - :returns: twilio.rest.api.v2010.account.token.TokenInstance - :rtype: twilio.rest.api.v2010.account.token.TokenInstance + Returns: + tuple: (payload, status_code, headers) """ - 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'), - } + data = values.of( + { + "Ttl": ttl, + } + ) + 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 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 await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def date_updated(self): + async def create_async( + self, ttl: Union[int, object] = values.unset + ) -> TokenInstance: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + Asynchronously create the TokenInstance - @property - def ice_servers(self): - """ - :returns: An array representing the ephemeral credentials - :rtype: unicode - """ - return self._properties['ice_servers'] + :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). - @property - def password(self): - """ - :returns: The temporary password used for authenticating - :rtype: unicode + :returns: The created TokenInstance """ - return self._properties['password'] + payload, _, _ = await self._create_async(ttl=ttl) + return TokenInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def ttl(self): - """ - :returns: The duration in seconds the credentials are valid - :rtype: unicode + async def create_with_http_info_async( + self, ttl: Union[int, object] = values.unset + ) -> ApiResponse: """ - return self._properties['ttl'] + Asynchronously create the TokenInstance and return response metadata - @property - def username(self): - """ - :returns: The temporary username that uniquely identifies a Token - :rtype: unicode + :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['username'] + payload, status_code, headers = await self._create_async(ttl=ttl) + instance = TokenInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 2e54887e5f..341c4ffdb3 100644 --- a/twilio/rest/api/v2010/account/transcription.py +++ b/twilio/rest/api/v2010/account/transcription.py @@ -1,426 +1,807 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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" + + """ + :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, + } - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource + 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) + 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}/Transcriptions.json'.format(**self._solution) + :returns: TranscriptionContext for this TranscriptionInstance + """ + if self._context is None: + self._context = TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def delete(self) -> bool: """ - 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. + Deletes the TranscriptionInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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 """ - 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 TranscriptionInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - Lists TranscriptionInstance 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptionInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.transcription.TranscriptionInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.delete_with_http_info() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of TranscriptionInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the TranscriptionInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with success boolean, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.delete_with_http_info_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def fetch(self) -> "TranscriptionInstance": + """ + 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 - - :param str target_url: API-generated URL for the requested results page + return self._proxy.fetch() - :returns: Page of TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionPage + async def fetch_async(self) -> "TranscriptionInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronous coroutine to fetch the TranscriptionInstance + - return TranscriptionPage(self._version, response, self._solution) + :returns: The fetched TranscriptionInstance + """ + return await self._proxy.fetch_async() - def get(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a TranscriptionContext + Fetch the TranscriptionInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return TranscriptionContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.fetch_with_http_info() - def __call__(self, sid): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Constructs a TranscriptionContext + Asynchronous coroutine to fetch the TranscriptionInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return TranscriptionContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.fetch_with_http_info_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 TranscriptionPage(Page): - """ """ +class TranscriptionContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the TranscriptionPage - - :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 TranscriptionContext - :returns: twilio.rest.api.v2010.account.transcription.TranscriptionPage - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionPage + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. """ - super(TranscriptionPage, 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}/Transcriptions/{sid}.json".format( + **self._solution + ) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of TranscriptionInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: twilio.rest.api.v2010.account.transcription.TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionInstance + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return TranscriptionInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Deletes the TranscriptionInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the TranscriptionInstance and return response metadata -class TranscriptionContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, account_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the TranscriptionContext + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes 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: True if delete succeeds, False otherwise """ - super(TranscriptionContext, self).__init__(version) + success, _, _ = await self._delete_async() + return success - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Transcriptions/{sid}.json'.format(**self._solution) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def fetch(self): + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptionInstance: """ Fetch the TranscriptionInstance + :returns: The fetched TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TranscriptionInstance: + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the TranscriptionInstance + Asynchronous coroutine to fetch the TranscriptionInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 TranscriptionInstance(InstanceResource): - """ """ +class TranscriptionPage(Page): - class Status(object): - IN_PROGRESS = "in-progress" - COMPLETED = "completed" - FAILED = "failed" + def get_instance(self, payload: Dict[str, Any]) -> TranscriptionInstance: + """ + Build an instance of TranscriptionInstance - 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'), - } + :param payload: Payload response from the API + """ - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + return TranscriptionInstance( + 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: TranscriptionContext for this TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionContext + :returns: Machine friendly representation """ - if self._context is None: - self._context = TranscriptionContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + return "" - @property - def account_sid(self): + +class TranscriptionList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Initialize the TranscriptionList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resources to read. + """ - return self._properties['account_sid'] + super().__init__(version) - @property - def api_version(self): + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Transcriptions.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TranscriptionInstance]: """ - :returns: The API version used to create the transcription - :rtype: unicode + Streams TranscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['api_version'] + 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[TranscriptionInstance]: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + Asynchronously streams TranscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + Streams TranscriptionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def duration(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The duration of the transcribed audio in seconds. - :rtype: unicode + Asynchronously streams TranscriptionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['duration'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def price(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: """ - :returns: The charge for the transcription - :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['price'] - @property - def price_unit(self): + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: """ - :returns: The currency in which price is measured - :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['price_unit'] - @property - def recording_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID that identifies the transcription's recording - :rtype: unicode + Lists TranscriptionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['recording_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Asynchronously lists TranscriptionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The transcription type - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptionPage, status code, and headers """ - return self._properties['type'] + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TranscriptionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptionPage, status code, and headers """ - return self._properties['uri'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TranscriptionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - def fetch(self): + def get_page(self, target_url: str) -> TranscriptionPage: """ - Fetch the TranscriptionInstance + Retrieve a specific page of TranscriptionInstance records from the API. + Request is executed immediately - :returns: The fetched TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptionInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return TranscriptionPage(self._version, response, solution=self._solution) - def delete(self): + async def get_page_async(self, target_url: str) -> TranscriptionPage: """ - Deletes the TranscriptionInstance + Asynchronously retrieve a specific page of TranscriptionInstance 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 TranscriptionInstance """ - return self._proxy.delete() + response = await self._version.domain.twilio.request_async("GET", target_url) + return TranscriptionPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. + """ + return TranscriptionContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. + """ + return TranscriptionContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 5500a8222d..a721a595d3 100644 --- a/twilio/rest/api/v2010/account/usage/record/__init__.py +++ b/twilio/rest/api/v2010/account/usage/record/__init__.py @@ -1,16 +1,25 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource 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,704 +31,722 @@ from twilio.rest.api.v2010.account.usage.record.yesterday import YesterdayList +class RecordInstance(InstanceResource): + """ + :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: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :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[str] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordInstance: + """ + Build an instance of RecordInstance + + :param payload: Payload response from the API + """ + + return RecordInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class RecordList(ListResource): - """ """ - def __init__(self, version, account_sid): + def __init__(self, version: Version, account_sid: str): """ Initialize the RecordList - :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.record.RecordList - :rtype: twilio.rest.api.v2010.account.usage.record.RecordList """ - super(RecordList, self).__init__(version) + super().__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): + 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[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RecordInstance]: """ Streams RecordInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param RecordInstance.Category category: The usage category 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) + :param str 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 - :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'], + page_size=limits["page_size"], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + return self._version.stream(page, limits["limit"]) - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=values.unset, limit=None, - page_size=None): + async def stream_async( + self, + category: Union[str, 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]: """ - Lists RecordInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronously streams RecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :param RecordInstance.Category category: The usage category 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) + :param str 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 - :rtype: list[twilio.rest.api.v2010.account.usage.record.RecordInstance] """ - return list(self.stream( + 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, - 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, + page_size=limits["page_size"], ) - return RecordPage(self._version, response, self._solution) + return self._version.stream_async(page, limits["limit"]) - @property - def all_time(self): + def stream_with_http_info( + self, + category: Union[str, 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, + ) -> tuple: """ - Access the all_time + Streams RecordInstance and returns headers from first page - :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 + :param str 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: twilio.rest.api.v2010.account.usage.record.daily.DailyList - :rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyList + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - 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 + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) - :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 + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - @property - def monthly(self): + async def stream_with_http_info_async( + self, + category: Union[str, 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, + ) -> tuple: """ - Access the monthly + Asynchronously streams RecordInstance and returns headers from first page - :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 + :param str 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: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthList - :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthList + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - if self._this_month is None: - self._this_month = ThisMonthList(self._version, account_sid=self._solution['account_sid'], ) - return self._this_month + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) - @property - def today(self): - """ - Access the today + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: twilio.rest.api.v2010.account.usage.record.today.TodayList - :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayList + def list( + self, + category: Union[str, 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]: """ - 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 + Lists RecordInstance 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.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 + :param str 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, + ) + ) - @property - def yesterday(self): - """ - Access the yesterday + async def list_async( + self, + category: Union[str, 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. - :returns: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayList - :rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayList + :param str 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 list_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Lists RecordInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously lists RecordInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + category: Union[str, 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: """ - if self._yesterday is None: - self._yesterday = YesterdayList(self._version, account_sid=self._solution['account_sid'], ) - return self._yesterday + Retrieve a single page of RecordInstance records from the API. + Request is executed immediately - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Page of RecordInstance """ - return '' + 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"}) -class RecordPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the RecordPage + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordPage(self._version, response, solution=self._solution) + + async def page_async( + self, + category: Union[str, 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 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 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: twilio.rest.api.v2010.account.usage.record.RecordPage - :rtype: twilio.rest.api.v2010.account.usage.record.RecordPage + :returns: Page of RecordInstance """ - super(RecordPage, self).__init__(version, response) + 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, + } + ) - # Path Solution - self._solution = solution + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def get_instance(self, payload): - """ - Build an instance of RecordInstance + headers["Accept"] = "application/json" - :param dict payload: Payload response from the API + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with RecordPage, status code, and headers + """ + 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, + } + ) - :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'], ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def __repr__(self): - """ - Provide a friendly representation + headers["Accept"] = "application/json" - :returns: Machine friendly representation - :rtype: str - """ - return '' + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RecordPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with RecordPage, status code, and headers + """ + 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"}) -class RecordInstance(InstanceResource): - """ """ - - class Category(object): - AGENT_CONFERENCE = "agent-conference" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - 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_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" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IP_MESSAGING = "ip-messaging" - IP_MESSAGING_COMMANDS = "ip-messaging-commands" - IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" - IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" - IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = "marketplace-algorithmia-named-entity-recognition" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = "marketplace-ibm-watson-message-insights" - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = "marketplace-ibm-watson-message-sentiment" - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = "marketplace-ibm-watson-recording-analysis" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" - MARKETPLACE_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_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = "marketplace-twilio-caller-name-lookup-us" - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = "marketplace-twilio-carrier-information-lookup" - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = "marketplace-whitepages-pro-caller-identification" - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = "marketplace-whitepages-pro-phone-intelligence" - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = "marketplace-whitepages-pro-phone-reputation" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_ACTIONS = "pchat-actions" - PCHAT_APS = "pchat-aps" - PCHAT_NOTIFICATIONS = "pchat-notifications" - PCHAT_READS = "pchat-reads" - PCHAT_USERS = "pchat-users" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VIDEO_RECORDINGS = "video-recordings" - 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" - WIRELESS = "wireless" - 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_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = "wireless-usage-commands-centralandsouthamerica" - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = "wireless-usage-data-centralandsouthamerica" - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = "wireless-usage-data-custom-additionalmb" - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = "wireless-usage-data-individual-additionalgb" - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = "wireless-usage-data-individual-firstgb" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = "wireless-usage-data-international-roaming-canada" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = "wireless-usage-data-international-roaming-india" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = "wireless-usage-data-international-roaming-mexico" - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - - 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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RecordPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def account_sid(self): + def get_page(self, target_url: str) -> RecordPage: """ - :returns: The SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + Retrieve a specific page of RecordInstance records from the API. + Request is executed immediately - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode - """ - return self._properties['api_version'] + :param target_url: API-generated URL for the requested results page - @property - def as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode - """ - return self._properties['as_of'] - - @property - def category(self): - """ - :returns: The category of usage - :rtype: RecordInstance.Category + :returns: Page of RecordInstance """ - return self._properties['category'] + response = self._version.domain.twilio.request("GET", target_url) + return RecordPage(self._version, response, solution=self._solution) - @property - def count(self): + async def get_page_async(self, target_url: str) -> RecordPage: """ - :returns: The number of usage events - :rtype: unicode - """ - return self._properties['count'] + Asynchronously retrieve a specific page of RecordInstance records from the API. + Request is executed immediately - @property - def count_unit(self): - """ - :returns: The units in which count is measured - :rtype: unicode - """ - return self._properties['count_unit'] + :param target_url: API-generated URL for the requested results page - @property - def description(self): - """ - :returns: A plain-language description of the usage category - :rtype: unicode + :returns: Page of RecordInstance """ - return self._properties['description'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return RecordPage(self._version, response, solution=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 0ca111d30d..3d01ff38a2 100644 --- a/twilio/rest/api/v2010/account/usage/record/all_time.py +++ b/twilio/rest/api/v2010/account/usage/record/all_time.py @@ -1,611 +1,647 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class AllTimeInstance(InstanceResource): + """ + :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: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :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[str] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AllTimePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AllTimeInstance: + """ + Build an instance of AllTimeInstance + + :param payload: Payload response from the API + """ + + return AllTimeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class AllTimeList(ListResource): - """ """ - def __init__(self, version, account_sid): + def __init__(self, version: Version, account_sid: str): """ Initialize the AllTimeList - :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.record.all_time.AllTimeList - :rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeList """ - super(AllTimeList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Usage/Records/AllTime.json'.format(**self._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): + def stream( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AllTimeInstance]: """ Streams AllTimeInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param AllTimeInstance.Category category: The usage category 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) + :param str 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 - :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'], + page_size=limits["page_size"], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + return self._version.stream(page, limits["limit"]) - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=values.unset, limit=None, - page_size=None): + async def stream_async( + self, + category: Union[str, 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]: """ - Lists AllTimeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + 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 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) + :param str 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 - :rtype: list[twilio.rest.api.v2010.account.usage.record.all_time.AllTimeInstance] """ - return list(self.stream( + 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, - 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 + page_size=limits["page_size"], + ) - :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 + return self._version.stream_async(page, limits["limit"]) - :returns: Page of AllTimeInstance - :rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimePage + def stream_with_http_info( + self, + category: Union[str, 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, + ) -> tuple: """ - 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, - }) + Streams AllTimeInstance and returns headers from first page - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return AllTimePage(self._version, response, self._solution) + :param str 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) - def get_page(self, target_url): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - 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, + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], ) - return AllTimePage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: Machine friendly representation - :rtype: str + async def stream_with_http_info_async( + self, + category: Union[str, 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, + ) -> tuple: """ - return '' + Asynchronously streams AllTimeInstance and returns headers from first page -class AllTimePage(Page): - """ """ + :param str 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) - def __init__(self, version, response, solution): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Initialize the AllTimePage + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) - :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. + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: twilio.rest.api.v2010.account.usage.record.all_time.AllTimePage - :rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimePage + def list( + self, + category: Union[str, 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]: """ - super(AllTimePage, self).__init__(version, response) - - # Path Solution - self._solution = solution + Lists AllTimeInstance 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): - """ - Build an instance of AllTimeInstance + :param str 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, + ) + ) - :param dict payload: Payload response from the API + async def list_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AllTimeInstance]: + """ + Asynchronously lists AllTimeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeInstance - :rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeInstance + :param str 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 list_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Lists AllTimeInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously lists AllTimeInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + category: Union[str, 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: """ - return AllTimeInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Retrieve a single page of AllTimeInstance records from the API. + Request is executed immediately - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Page of AllTimeInstance """ - return '' + 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"}) -class AllTimeInstance(InstanceResource): - """ """ - - class Category(object): - AGENT_CONFERENCE = "agent-conference" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - 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_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" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IP_MESSAGING = "ip-messaging" - IP_MESSAGING_COMMANDS = "ip-messaging-commands" - IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" - IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" - IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = "marketplace-algorithmia-named-entity-recognition" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = "marketplace-ibm-watson-message-insights" - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = "marketplace-ibm-watson-message-sentiment" - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = "marketplace-ibm-watson-recording-analysis" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" - MARKETPLACE_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_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = "marketplace-twilio-caller-name-lookup-us" - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = "marketplace-twilio-carrier-information-lookup" - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = "marketplace-whitepages-pro-caller-identification" - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = "marketplace-whitepages-pro-phone-intelligence" - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = "marketplace-whitepages-pro-phone-reputation" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_ACTIONS = "pchat-actions" - PCHAT_APS = "pchat-aps" - PCHAT_NOTIFICATIONS = "pchat-notifications" - PCHAT_READS = "pchat-reads" - PCHAT_USERS = "pchat-users" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VIDEO_RECORDINGS = "video-recordings" - 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" - WIRELESS = "wireless" - 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_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = "wireless-usage-commands-centralandsouthamerica" - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = "wireless-usage-data-centralandsouthamerica" - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = "wireless-usage-data-custom-additionalmb" - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = "wireless-usage-data-individual-additionalgb" - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = "wireless-usage-data-individual-firstgb" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = "wireless-usage-data-international-roaming-canada" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = "wireless-usage-data-international-roaming-india" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = "wireless-usage-data-international-roaming-mexico" - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - - def __init__(self, version, payload, account_sid): - """ - Initialize the AllTimeInstance - - :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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AllTimePage(self._version, response, solution=self._solution) + + async def page_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AllTimePage: + """ + Asynchronously retrieve a single page of AllTimeInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + :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 - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + :returns: Page of AllTimeInstance """ - return self._properties['api_version'] + 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 as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode - """ - return self._properties['as_of'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def category(self): - """ - :returns: The category of usage - :rtype: AllTimeInstance.Category - """ - return self._properties['category'] + headers["Accept"] = "application/json" - @property - def count(self): - """ - :returns: The number of usage events - :rtype: unicode - """ - return self._properties['count'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AllTimePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with AllTimePage, status code, and headers + """ + 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 count_unit(self): - """ - :returns: The units in which count is measured - :rtype: unicode - """ - return self._properties['count_unit'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def description(self): - """ - :returns: A plain-language description of the usage category - :rtype: unicode - """ - return self._properties['description'] + headers["Accept"] = "application/json" - @property - def end_date(self): - """ - :returns: The last date for which usage is included in the UsageRecord - :rtype: date - """ - return self._properties['end_date'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AllTimePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with AllTimePage, status code, and headers + """ + 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 price(self): - """ - :returns: The total price of the usage - :rtype: unicode - """ - return self._properties['price'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def price_unit(self): - """ - :returns: The currency in which `price` is measured - :rtype: unicode - """ - return self._properties['price_unit'] + headers["Accept"] = "application/json" - @property - def start_date(self): - """ - :returns: The first date for which usage is included in this UsageRecord - :rtype: date - """ - return self._properties['start_date'] + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AllTimePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def subresource_uris(self): + def get_page(self, target_url: str) -> AllTimePage: """ - :returns: A list of related resources identified by their relative URIs - :rtype: unicode - """ - return self._properties['subresource_uris'] + Retrieve a specific page of AllTimeInstance 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 target_url: API-generated URL for the requested results page - @property - def usage(self): - """ - :returns: The amount of usage - :rtype: unicode + :returns: Page of AllTimeInstance """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return AllTimePage(self._version, response, solution=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, solution=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 8025c09e60..0be683fb86 100644 --- a/twilio/rest/api/v2010/account/usage/record/daily.py +++ b/twilio/rest/api/v2010/account/usage/record/daily.py @@ -1,611 +1,647 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class DailyInstance(InstanceResource): + """ + :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: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :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[str] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DailyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DailyInstance: + """ + Build an instance of DailyInstance + + :param payload: Payload response from the API + """ + + return DailyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class DailyList(ListResource): - """ """ - def __init__(self, version, account_sid): + def __init__(self, version: Version, account_sid: str): """ Initialize the DailyList - :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.record.daily.DailyList - :rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyList """ - super(DailyList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Usage/Records/Daily.json'.format(**self._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): + def stream( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DailyInstance]: """ Streams DailyInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param DailyInstance.Category category: The usage category 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) + :param str 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 - :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'], + page_size=limits["page_size"], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + return self._version.stream(page, limits["limit"]) - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=values.unset, limit=None, - page_size=None): + async def stream_async( + self, + category: Union[str, 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]: """ - Lists DailyInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + 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 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) + :param str 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 - :rtype: list[twilio.rest.api.v2010.account.usage.record.daily.DailyInstance] """ - return list(self.stream( + 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, - 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 + page_size=limits["page_size"], + ) - :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 + return self._version.stream_async(page, limits["limit"]) - :returns: Page of DailyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyPage + def stream_with_http_info( + self, + category: Union[str, 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, + ) -> tuple: """ - 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, - }) + Streams DailyInstance and returns headers from first page - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return DailyPage(self._version, response, self._solution) + :param str 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) - def get_page(self, target_url): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - 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, + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], ) - return DailyPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: Machine friendly representation - :rtype: str + async def stream_with_http_info_async( + self, + category: Union[str, 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, + ) -> tuple: """ - return '' + Asynchronously streams DailyInstance and returns headers from first page -class DailyPage(Page): - """ """ + :param str 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) - def __init__(self, version, response, solution): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Initialize the DailyPage + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) - :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. + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: twilio.rest.api.v2010.account.usage.record.daily.DailyPage - :rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyPage + def list( + self, + category: Union[str, 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]: """ - super(DailyPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + Lists DailyInstance 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): - """ - Build an instance of DailyInstance + :param str 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, + ) + ) - :param dict payload: Payload response from the API + async def list_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DailyInstance]: + """ + Asynchronously lists DailyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: twilio.rest.api.v2010.account.usage.record.daily.DailyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyInstance + :param str 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 list_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Lists DailyInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously lists DailyInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + category: Union[str, 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: """ - return DailyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Retrieve a single page of DailyInstance records from the API. + Request is executed immediately - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Page of DailyInstance """ - return '' + 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"}) -class DailyInstance(InstanceResource): - """ """ - - class Category(object): - AGENT_CONFERENCE = "agent-conference" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - 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_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" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IP_MESSAGING = "ip-messaging" - IP_MESSAGING_COMMANDS = "ip-messaging-commands" - IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" - IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" - IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = "marketplace-algorithmia-named-entity-recognition" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = "marketplace-ibm-watson-message-insights" - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = "marketplace-ibm-watson-message-sentiment" - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = "marketplace-ibm-watson-recording-analysis" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" - MARKETPLACE_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_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = "marketplace-twilio-caller-name-lookup-us" - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = "marketplace-twilio-carrier-information-lookup" - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = "marketplace-whitepages-pro-caller-identification" - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = "marketplace-whitepages-pro-phone-intelligence" - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = "marketplace-whitepages-pro-phone-reputation" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_ACTIONS = "pchat-actions" - PCHAT_APS = "pchat-aps" - PCHAT_NOTIFICATIONS = "pchat-notifications" - PCHAT_READS = "pchat-reads" - PCHAT_USERS = "pchat-users" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VIDEO_RECORDINGS = "video-recordings" - 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" - WIRELESS = "wireless" - 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_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = "wireless-usage-commands-centralandsouthamerica" - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = "wireless-usage-data-centralandsouthamerica" - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = "wireless-usage-data-custom-additionalmb" - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = "wireless-usage-data-individual-additionalgb" - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = "wireless-usage-data-individual-firstgb" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = "wireless-usage-data-international-roaming-canada" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = "wireless-usage-data-international-roaming-india" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = "wireless-usage-data-international-roaming-mexico" - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - - def __init__(self, version, payload, account_sid): - """ - Initialize the DailyInstance - - :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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DailyPage(self._version, response, solution=self._solution) + + async def page_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DailyPage: + """ + Asynchronously retrieve a single page of DailyInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + :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 - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + :returns: Page of DailyInstance """ - return self._properties['api_version'] + 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 as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode - """ - return self._properties['as_of'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def category(self): - """ - :returns: The category of usage - :rtype: DailyInstance.Category - """ - return self._properties['category'] + headers["Accept"] = "application/json" - @property - def count(self): - """ - :returns: The number of usage events - :rtype: unicode - """ - return self._properties['count'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DailyPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with DailyPage, status code, and headers + """ + 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 count_unit(self): - """ - :returns: The units in which count is measured - :rtype: unicode - """ - return self._properties['count_unit'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def description(self): - """ - :returns: A plain-language description of the usage category - :rtype: unicode - """ - return self._properties['description'] + headers["Accept"] = "application/json" - @property - def end_date(self): - """ - :returns: The last date for which usage is included in the UsageRecord - :rtype: date - """ - return self._properties['end_date'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DailyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with DailyPage, status code, and headers + """ + 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 price(self): - """ - :returns: The total price of the usage - :rtype: unicode - """ - return self._properties['price'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def price_unit(self): - """ - :returns: The currency in which `price` is measured - :rtype: unicode - """ - return self._properties['price_unit'] + headers["Accept"] = "application/json" - @property - def start_date(self): - """ - :returns: The first date for which usage is included in this UsageRecord - :rtype: date - """ - return self._properties['start_date'] + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DailyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def subresource_uris(self): + def get_page(self, target_url: str) -> DailyPage: """ - :returns: A list of related resources identified by their relative URIs - :rtype: unicode - """ - return self._properties['subresource_uris'] + Retrieve a specific page of DailyInstance 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 target_url: API-generated URL for the requested results page - @property - def usage(self): - """ - :returns: The amount of usage - :rtype: unicode + :returns: Page of DailyInstance """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return DailyPage(self._version, response, solution=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, solution=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 a4e69e1bf2..25cc8a5ce1 100644 --- a/twilio/rest/api/v2010/account/usage/record/last_month.py +++ b/twilio/rest/api/v2010/account/usage/record/last_month.py @@ -1,611 +1,647 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class LastMonthInstance(InstanceResource): + """ + :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: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :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[str] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class LastMonthPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> LastMonthInstance: + """ + Build an instance of LastMonthInstance + + :param payload: Payload response from the API + """ + + return LastMonthInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class LastMonthList(ListResource): - """ """ - def __init__(self, version, account_sid): + def __init__(self, version: Version, account_sid: str): """ Initialize the LastMonthList - :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.record.last_month.LastMonthList - :rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthList """ - super(LastMonthList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Usage/Records/LastMonth.json'.format(**self._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): + def stream( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[LastMonthInstance]: """ Streams LastMonthInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param LastMonthInstance.Category category: The usage category 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) + :param str 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 - :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'], + page_size=limits["page_size"], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + return self._version.stream(page, limits["limit"]) - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=values.unset, limit=None, - page_size=None): + async def stream_async( + self, + category: Union[str, 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]: """ - Lists LastMonthInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + 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 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) + :param str 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 - :rtype: list[twilio.rest.api.v2010.account.usage.record.last_month.LastMonthInstance] """ - return list(self.stream( + 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, - 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 + page_size=limits["page_size"], + ) - :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 + return self._version.stream_async(page, limits["limit"]) - :returns: Page of LastMonthInstance - :rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthPage + def stream_with_http_info( + self, + category: Union[str, 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, + ) -> tuple: """ - 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, - }) + Streams LastMonthInstance and returns headers from first page - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return LastMonthPage(self._version, response, self._solution) + :param str 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) - def get_page(self, target_url): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - 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, + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], ) - return LastMonthPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: Machine friendly representation - :rtype: str + async def stream_with_http_info_async( + self, + category: Union[str, 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, + ) -> tuple: """ - return '' + Asynchronously streams LastMonthInstance and returns headers from first page -class LastMonthPage(Page): - """ """ + :param str 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) - def __init__(self, version, response, solution): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Initialize the LastMonthPage + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) - :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. + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthPage - :rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthPage + def list( + self, + category: Union[str, 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]: """ - super(LastMonthPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + Lists LastMonthInstance 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): - """ - Build an instance of LastMonthInstance + :param str 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, + ) + ) - :param dict payload: Payload response from the API + async def list_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LastMonthInstance]: + """ + Asynchronously lists LastMonthInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthInstance - :rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthInstance + :param str 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 list_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Lists LastMonthInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously lists LastMonthInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + category: Union[str, 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: """ - return LastMonthInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Retrieve a single page of LastMonthInstance records from the API. + Request is executed immediately - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Page of LastMonthInstance """ - return '' + 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"}) -class LastMonthInstance(InstanceResource): - """ """ - - class Category(object): - AGENT_CONFERENCE = "agent-conference" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - 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_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" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IP_MESSAGING = "ip-messaging" - IP_MESSAGING_COMMANDS = "ip-messaging-commands" - IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" - IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" - IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = "marketplace-algorithmia-named-entity-recognition" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = "marketplace-ibm-watson-message-insights" - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = "marketplace-ibm-watson-message-sentiment" - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = "marketplace-ibm-watson-recording-analysis" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" - MARKETPLACE_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_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = "marketplace-twilio-caller-name-lookup-us" - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = "marketplace-twilio-carrier-information-lookup" - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = "marketplace-whitepages-pro-caller-identification" - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = "marketplace-whitepages-pro-phone-intelligence" - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = "marketplace-whitepages-pro-phone-reputation" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_ACTIONS = "pchat-actions" - PCHAT_APS = "pchat-aps" - PCHAT_NOTIFICATIONS = "pchat-notifications" - PCHAT_READS = "pchat-reads" - PCHAT_USERS = "pchat-users" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VIDEO_RECORDINGS = "video-recordings" - 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" - WIRELESS = "wireless" - 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_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = "wireless-usage-commands-centralandsouthamerica" - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = "wireless-usage-data-centralandsouthamerica" - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = "wireless-usage-data-custom-additionalmb" - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = "wireless-usage-data-individual-additionalgb" - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = "wireless-usage-data-individual-firstgb" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = "wireless-usage-data-international-roaming-canada" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = "wireless-usage-data-international-roaming-india" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = "wireless-usage-data-international-roaming-mexico" - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - - def __init__(self, version, payload, account_sid): - """ - Initialize the LastMonthInstance - - :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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LastMonthPage(self._version, response, solution=self._solution) + + async def page_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LastMonthPage: + """ + Asynchronously retrieve a single page of LastMonthInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + :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 - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + :returns: Page of LastMonthInstance """ - return self._properties['api_version'] + 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 as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode - """ - return self._properties['as_of'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def category(self): - """ - :returns: The category of usage - :rtype: LastMonthInstance.Category - """ - return self._properties['category'] + headers["Accept"] = "application/json" - @property - def count(self): - """ - :returns: The number of usage events - :rtype: unicode - """ - return self._properties['count'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LastMonthPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with LastMonthPage, status code, and headers + """ + 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 count_unit(self): - """ - :returns: The units in which count is measured - :rtype: unicode - """ - return self._properties['count_unit'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def description(self): - """ - :returns: A plain-language description of the usage category - :rtype: unicode - """ - return self._properties['description'] + headers["Accept"] = "application/json" - @property - def end_date(self): - """ - :returns: The last date for which usage is included in the UsageRecord - :rtype: date - """ - return self._properties['end_date'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = LastMonthPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with LastMonthPage, status code, and headers + """ + 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 price(self): - """ - :returns: The total price of the usage - :rtype: unicode - """ - return self._properties['price'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def price_unit(self): - """ - :returns: The currency in which `price` is measured - :rtype: unicode - """ - return self._properties['price_unit'] + headers["Accept"] = "application/json" - @property - def start_date(self): - """ - :returns: The first date for which usage is included in this UsageRecord - :rtype: date - """ - return self._properties['start_date'] + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = LastMonthPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def subresource_uris(self): + def get_page(self, target_url: str) -> LastMonthPage: """ - :returns: A list of related resources identified by their relative URIs - :rtype: unicode - """ - return self._properties['subresource_uris'] + Retrieve a specific page of LastMonthInstance 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 target_url: API-generated URL for the requested results page - @property - def usage(self): - """ - :returns: The amount of usage - :rtype: unicode + :returns: Page of LastMonthInstance """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return LastMonthPage(self._version, response, solution=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, solution=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 77da9bd9b9..9d597023be 100644 --- a/twilio/rest/api/v2010/account/usage/record/monthly.py +++ b/twilio/rest/api/v2010/account/usage/record/monthly.py @@ -1,611 +1,647 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class MonthlyInstance(InstanceResource): + """ + :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: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :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[str] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MonthlyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MonthlyInstance: + """ + Build an instance of MonthlyInstance + + :param payload: Payload response from the API + """ + + return MonthlyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class MonthlyList(ListResource): - """ """ - def __init__(self, version, account_sid): + def __init__(self, version: Version, account_sid: str): """ Initialize the MonthlyList - :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.record.monthly.MonthlyList - :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList """ - super(MonthlyList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Usage/Records/Monthly.json'.format(**self._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): + def stream( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MonthlyInstance]: """ Streams MonthlyInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param MonthlyInstance.Category category: The usage category 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) + :param str 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 - :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'], + page_size=limits["page_size"], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + return self._version.stream(page, limits["limit"]) - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=values.unset, limit=None, - page_size=None): + async def stream_async( + self, + category: Union[str, 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]: """ - Lists MonthlyInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + 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 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) + :param str 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 - :rtype: list[twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance] """ - return list(self.stream( + 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, - 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 + page_size=limits["page_size"], + ) - :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 + return self._version.stream_async(page, limits["limit"]) - :returns: Page of MonthlyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyPage + def stream_with_http_info( + self, + category: Union[str, 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, + ) -> tuple: """ - 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, - }) + Streams MonthlyInstance and returns headers from first page - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return MonthlyPage(self._version, response, self._solution) + :param str 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) - def get_page(self, target_url): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - 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, + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], ) - return MonthlyPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: Machine friendly representation - :rtype: str + async def stream_with_http_info_async( + self, + category: Union[str, 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, + ) -> tuple: """ - return '' + Asynchronously streams MonthlyInstance and returns headers from first page -class MonthlyPage(Page): - """ """ + :param str 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) - def __init__(self, version, response, solution): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Initialize the MonthlyPage + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) - :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. + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyPage - :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyPage + def list( + self, + category: Union[str, 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]: """ - super(MonthlyPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + Lists MonthlyInstance 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): - """ - Build an instance of MonthlyInstance + :param str 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, + ) + ) - :param dict payload: Payload response from the API + async def list_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MonthlyInstance]: + """ + Asynchronously lists MonthlyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance + :param str 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 list_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Lists MonthlyInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously lists MonthlyInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + category: Union[str, 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: """ - return MonthlyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Retrieve a single page of MonthlyInstance records from the API. + Request is executed immediately - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Page of MonthlyInstance """ - return '' + 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"}) -class MonthlyInstance(InstanceResource): - """ """ - - class Category(object): - AGENT_CONFERENCE = "agent-conference" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - 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_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" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IP_MESSAGING = "ip-messaging" - IP_MESSAGING_COMMANDS = "ip-messaging-commands" - IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" - IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" - IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = "marketplace-algorithmia-named-entity-recognition" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = "marketplace-ibm-watson-message-insights" - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = "marketplace-ibm-watson-message-sentiment" - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = "marketplace-ibm-watson-recording-analysis" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" - MARKETPLACE_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_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = "marketplace-twilio-caller-name-lookup-us" - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = "marketplace-twilio-carrier-information-lookup" - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = "marketplace-whitepages-pro-caller-identification" - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = "marketplace-whitepages-pro-phone-intelligence" - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = "marketplace-whitepages-pro-phone-reputation" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_ACTIONS = "pchat-actions" - PCHAT_APS = "pchat-aps" - PCHAT_NOTIFICATIONS = "pchat-notifications" - PCHAT_READS = "pchat-reads" - PCHAT_USERS = "pchat-users" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VIDEO_RECORDINGS = "video-recordings" - 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" - WIRELESS = "wireless" - 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_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = "wireless-usage-commands-centralandsouthamerica" - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = "wireless-usage-data-centralandsouthamerica" - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = "wireless-usage-data-custom-additionalmb" - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = "wireless-usage-data-individual-additionalgb" - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = "wireless-usage-data-individual-firstgb" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = "wireless-usage-data-international-roaming-canada" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = "wireless-usage-data-international-roaming-india" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = "wireless-usage-data-international-roaming-mexico" - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - - def __init__(self, version, payload, account_sid): - """ - Initialize the MonthlyInstance - - :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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MonthlyPage(self._version, response, solution=self._solution) + + async def page_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MonthlyPage: + """ + Asynchronously retrieve a single page of MonthlyInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + :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 - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + :returns: Page of MonthlyInstance """ - return self._properties['api_version'] + 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 as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode - """ - return self._properties['as_of'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def category(self): - """ - :returns: The category of usage - :rtype: MonthlyInstance.Category - """ - return self._properties['category'] + headers["Accept"] = "application/json" - @property - def count(self): - """ - :returns: The number of usage events - :rtype: unicode - """ - return self._properties['count'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MonthlyPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with MonthlyPage, status code, and headers + """ + 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 count_unit(self): - """ - :returns: The units in which count is measured - :rtype: unicode - """ - return self._properties['count_unit'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def description(self): - """ - :returns: A plain-language description of the usage category - :rtype: unicode - """ - return self._properties['description'] + headers["Accept"] = "application/json" - @property - def end_date(self): - """ - :returns: The last date for which usage is included in the UsageRecord - :rtype: date - """ - return self._properties['end_date'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MonthlyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with MonthlyPage, status code, and headers + """ + 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 price(self): - """ - :returns: The total price of the usage - :rtype: unicode - """ - return self._properties['price'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def price_unit(self): - """ - :returns: The currency in which `price` is measured - :rtype: unicode - """ - return self._properties['price_unit'] + headers["Accept"] = "application/json" - @property - def start_date(self): - """ - :returns: The first date for which usage is included in this UsageRecord - :rtype: date - """ - return self._properties['start_date'] + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MonthlyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def subresource_uris(self): + def get_page(self, target_url: str) -> MonthlyPage: """ - :returns: A list of related resources identified by their relative URIs - :rtype: unicode - """ - return self._properties['subresource_uris'] + Retrieve a specific page of MonthlyInstance 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 target_url: API-generated URL for the requested results page - @property - def usage(self): - """ - :returns: The amount of usage - :rtype: unicode + :returns: Page of MonthlyInstance """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return MonthlyPage(self._version, response, solution=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, solution=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 838ed389ec..b1f11399bd 100644 --- a/twilio/rest/api/v2010/account/usage/record/this_month.py +++ b/twilio/rest/api/v2010/account/usage/record/this_month.py @@ -1,611 +1,647 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class ThisMonthInstance(InstanceResource): + """ + :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: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :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[str] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ThisMonthPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ThisMonthInstance: + """ + Build an instance of ThisMonthInstance + + :param payload: Payload response from the API + """ + + return ThisMonthInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class ThisMonthList(ListResource): - """ """ - def __init__(self, version, account_sid): + def __init__(self, version: Version, account_sid: str): """ Initialize the ThisMonthList - :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.record.this_month.ThisMonthList - :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthList """ - super(ThisMonthList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Usage/Records/ThisMonth.json'.format(**self._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): + def stream( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ThisMonthInstance]: """ Streams ThisMonthInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param ThisMonthInstance.Category category: The usage category 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) + :param str 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 - :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'], + page_size=limits["page_size"], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + return self._version.stream(page, limits["limit"]) - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=values.unset, limit=None, - page_size=None): + async def stream_async( + self, + category: Union[str, 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]: """ - Lists ThisMonthInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + 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 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) + :param str 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 - :rtype: list[twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance] """ - return list(self.stream( + 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, - 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 + page_size=limits["page_size"], + ) - :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 + return self._version.stream_async(page, limits["limit"]) - :returns: Page of ThisMonthInstance - :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthPage + def stream_with_http_info( + self, + category: Union[str, 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, + ) -> tuple: """ - 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, - }) + Streams ThisMonthInstance and returns headers from first page - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return ThisMonthPage(self._version, response, self._solution) + :param str 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) - def get_page(self, target_url): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - 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, + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], ) - return ThisMonthPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: Machine friendly representation - :rtype: str + async def stream_with_http_info_async( + self, + category: Union[str, 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, + ) -> tuple: """ - return '' + Asynchronously streams ThisMonthInstance and returns headers from first page -class ThisMonthPage(Page): - """ """ + :param str 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) - def __init__(self, version, response, solution): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Initialize the ThisMonthPage + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) - :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. + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthPage - :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthPage + def list( + self, + category: Union[str, 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]: """ - super(ThisMonthPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + Lists ThisMonthInstance 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): - """ - Build an instance of ThisMonthInstance + :param str 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, + ) + ) - :param dict payload: Payload response from the API + async def list_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ThisMonthInstance]: + """ + Asynchronously lists ThisMonthInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance - :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance + :param str 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 list_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Lists ThisMonthInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously lists ThisMonthInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + category: Union[str, 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: """ - return ThisMonthInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Retrieve a single page of ThisMonthInstance records from the API. + Request is executed immediately - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Page of ThisMonthInstance """ - return '' + 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"}) -class ThisMonthInstance(InstanceResource): - """ """ - - class Category(object): - AGENT_CONFERENCE = "agent-conference" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - 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_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" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IP_MESSAGING = "ip-messaging" - IP_MESSAGING_COMMANDS = "ip-messaging-commands" - IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" - IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" - IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = "marketplace-algorithmia-named-entity-recognition" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = "marketplace-ibm-watson-message-insights" - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = "marketplace-ibm-watson-message-sentiment" - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = "marketplace-ibm-watson-recording-analysis" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" - MARKETPLACE_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_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = "marketplace-twilio-caller-name-lookup-us" - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = "marketplace-twilio-carrier-information-lookup" - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = "marketplace-whitepages-pro-caller-identification" - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = "marketplace-whitepages-pro-phone-intelligence" - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = "marketplace-whitepages-pro-phone-reputation" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_ACTIONS = "pchat-actions" - PCHAT_APS = "pchat-aps" - PCHAT_NOTIFICATIONS = "pchat-notifications" - PCHAT_READS = "pchat-reads" - PCHAT_USERS = "pchat-users" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VIDEO_RECORDINGS = "video-recordings" - 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" - WIRELESS = "wireless" - 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_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = "wireless-usage-commands-centralandsouthamerica" - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = "wireless-usage-data-centralandsouthamerica" - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = "wireless-usage-data-custom-additionalmb" - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = "wireless-usage-data-individual-additionalgb" - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = "wireless-usage-data-individual-firstgb" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = "wireless-usage-data-international-roaming-canada" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = "wireless-usage-data-international-roaming-india" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = "wireless-usage-data-international-roaming-mexico" - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - - def __init__(self, version, payload, account_sid): - """ - Initialize the ThisMonthInstance - - :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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ThisMonthPage(self._version, response, solution=self._solution) + + async def page_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ThisMonthPage: + """ + Asynchronously retrieve a single page of ThisMonthInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + :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 - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + :returns: Page of ThisMonthInstance """ - return self._properties['api_version'] + 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 as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode - """ - return self._properties['as_of'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def category(self): - """ - :returns: The category of usage - :rtype: ThisMonthInstance.Category - """ - return self._properties['category'] + headers["Accept"] = "application/json" - @property - def count(self): - """ - :returns: The number of usage events - :rtype: unicode - """ - return self._properties['count'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ThisMonthPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ThisMonthPage, status code, and headers + """ + 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 count_unit(self): - """ - :returns: The units in which count is measured - :rtype: unicode - """ - return self._properties['count_unit'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def description(self): - """ - :returns: A plain-language description of the usage category - :rtype: unicode - """ - return self._properties['description'] + headers["Accept"] = "application/json" - @property - def end_date(self): - """ - :returns: The last date for which usage is included in the UsageRecord - :rtype: date - """ - return self._properties['end_date'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ThisMonthPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ThisMonthPage, status code, and headers + """ + 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 price(self): - """ - :returns: The total price of the usage - :rtype: unicode - """ - return self._properties['price'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def price_unit(self): - """ - :returns: The currency in which `price` is measured - :rtype: unicode - """ - return self._properties['price_unit'] + headers["Accept"] = "application/json" - @property - def start_date(self): - """ - :returns: The first date for which usage is included in this UsageRecord - :rtype: date - """ - return self._properties['start_date'] + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ThisMonthPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def subresource_uris(self): + def get_page(self, target_url: str) -> ThisMonthPage: """ - :returns: A list of related resources identified by their relative URIs - :rtype: unicode - """ - return self._properties['subresource_uris'] + Retrieve a specific page of ThisMonthInstance 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 target_url: API-generated URL for the requested results page - @property - def usage(self): - """ - :returns: The amount of usage - :rtype: unicode + :returns: Page of ThisMonthInstance """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return ThisMonthPage(self._version, response, solution=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, solution=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 d0e222b49f..dfe2e1fca4 100644 --- a/twilio/rest/api/v2010/account/usage/record/today.py +++ b/twilio/rest/api/v2010/account/usage/record/today.py @@ -1,611 +1,647 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class TodayInstance(InstanceResource): + """ + :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: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :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[str] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TodayPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TodayInstance: + """ + Build an instance of TodayInstance + + :param payload: Payload response from the API + """ + + return TodayInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class TodayList(ListResource): - """ """ - def __init__(self, version, account_sid): + def __init__(self, version: Version, account_sid: str): """ Initialize the TodayList - :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.record.today.TodayList - :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayList """ - super(TodayList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Usage/Records/Today.json'.format(**self._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): + def stream( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TodayInstance]: """ Streams TodayInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param TodayInstance.Category category: The usage category 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) + :param str 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 - :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'], + page_size=limits["page_size"], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + return self._version.stream(page, limits["limit"]) - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=values.unset, limit=None, - page_size=None): + async def stream_async( + self, + category: Union[str, 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]: """ - Lists TodayInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + 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 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) + :param str 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 - :rtype: list[twilio.rest.api.v2010.account.usage.record.today.TodayInstance] """ - return list(self.stream( + 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, - 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 + page_size=limits["page_size"], + ) - :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 + return self._version.stream_async(page, limits["limit"]) - :returns: Page of TodayInstance - :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayPage + def stream_with_http_info( + self, + category: Union[str, 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, + ) -> tuple: """ - 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, - }) + Streams TodayInstance and returns headers from first page - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return TodayPage(self._version, response, self._solution) + :param str 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) - def get_page(self, target_url): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - 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, + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], ) - return TodayPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: Machine friendly representation - :rtype: str + async def stream_with_http_info_async( + self, + category: Union[str, 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, + ) -> tuple: """ - return '' + Asynchronously streams TodayInstance and returns headers from first page -class TodayPage(Page): - """ """ + :param str 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) - def __init__(self, version, response, solution): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Initialize the TodayPage + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) - :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. + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: twilio.rest.api.v2010.account.usage.record.today.TodayPage - :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayPage + def list( + self, + category: Union[str, 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]: """ - super(TodayPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + Lists TodayInstance 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): - """ - Build an instance of TodayInstance + :param str 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, + ) + ) - :param dict payload: Payload response from the API + async def list_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TodayInstance]: + """ + Asynchronously lists TodayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: twilio.rest.api.v2010.account.usage.record.today.TodayInstance - :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayInstance + :param str 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 list_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Lists TodayInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously lists TodayInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + category: Union[str, 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: """ - return TodayInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Retrieve a single page of TodayInstance records from the API. + Request is executed immediately - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Page of TodayInstance """ - return '' + 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"}) -class TodayInstance(InstanceResource): - """ """ - - class Category(object): - AGENT_CONFERENCE = "agent-conference" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - 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_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" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IP_MESSAGING = "ip-messaging" - IP_MESSAGING_COMMANDS = "ip-messaging-commands" - IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" - IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" - IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = "marketplace-algorithmia-named-entity-recognition" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = "marketplace-ibm-watson-message-insights" - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = "marketplace-ibm-watson-message-sentiment" - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = "marketplace-ibm-watson-recording-analysis" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" - MARKETPLACE_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_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = "marketplace-twilio-caller-name-lookup-us" - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = "marketplace-twilio-carrier-information-lookup" - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = "marketplace-whitepages-pro-caller-identification" - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = "marketplace-whitepages-pro-phone-intelligence" - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = "marketplace-whitepages-pro-phone-reputation" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_ACTIONS = "pchat-actions" - PCHAT_APS = "pchat-aps" - PCHAT_NOTIFICATIONS = "pchat-notifications" - PCHAT_READS = "pchat-reads" - PCHAT_USERS = "pchat-users" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VIDEO_RECORDINGS = "video-recordings" - 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" - WIRELESS = "wireless" - 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_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = "wireless-usage-commands-centralandsouthamerica" - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = "wireless-usage-data-centralandsouthamerica" - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = "wireless-usage-data-custom-additionalmb" - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = "wireless-usage-data-individual-additionalgb" - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = "wireless-usage-data-individual-firstgb" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = "wireless-usage-data-international-roaming-canada" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = "wireless-usage-data-international-roaming-india" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = "wireless-usage-data-international-roaming-mexico" - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - - def __init__(self, version, payload, account_sid): - """ - Initialize the TodayInstance - - :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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TodayPage(self._version, response, solution=self._solution) + + async def page_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TodayPage: + """ + Asynchronously retrieve a single page of TodayInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + :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 - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + :returns: Page of TodayInstance """ - return self._properties['api_version'] + 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 as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode - """ - return self._properties['as_of'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def category(self): - """ - :returns: The category of usage - :rtype: TodayInstance.Category - """ - return self._properties['category'] + headers["Accept"] = "application/json" - @property - def count(self): - """ - :returns: The number of usage events - :rtype: unicode - """ - return self._properties['count'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TodayPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with TodayPage, status code, and headers + """ + 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 count_unit(self): - """ - :returns: The units in which count is measured - :rtype: unicode - """ - return self._properties['count_unit'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def description(self): - """ - :returns: A plain-language description of the usage category - :rtype: unicode - """ - return self._properties['description'] + headers["Accept"] = "application/json" - @property - def end_date(self): - """ - :returns: The last date for which usage is included in the UsageRecord - :rtype: date - """ - return self._properties['end_date'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TodayPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with TodayPage, status code, and headers + """ + 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 price(self): - """ - :returns: The total price of the usage - :rtype: unicode - """ - return self._properties['price'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def price_unit(self): - """ - :returns: The currency in which `price` is measured - :rtype: unicode - """ - return self._properties['price_unit'] + headers["Accept"] = "application/json" - @property - def start_date(self): - """ - :returns: The first date for which usage is included in this UsageRecord - :rtype: date - """ - return self._properties['start_date'] + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TodayPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def subresource_uris(self): + def get_page(self, target_url: str) -> TodayPage: """ - :returns: A list of related resources identified by their relative URIs - :rtype: unicode - """ - return self._properties['subresource_uris'] + Retrieve a specific page of TodayInstance 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 target_url: API-generated URL for the requested results page - @property - def usage(self): - """ - :returns: The amount of usage - :rtype: unicode + :returns: Page of TodayInstance """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return TodayPage(self._version, response, solution=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, solution=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 652fcb5ded..24812d72a3 100644 --- a/twilio/rest/api/v2010/account/usage/record/yearly.py +++ b/twilio/rest/api/v2010/account/usage/record/yearly.py @@ -1,611 +1,647 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class YearlyInstance(InstanceResource): + """ + :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: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :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[str] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class YearlyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> YearlyInstance: + """ + Build an instance of YearlyInstance + + :param payload: Payload response from the API + """ + + return YearlyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class YearlyList(ListResource): - """ """ - def __init__(self, version, account_sid): + def __init__(self, version: Version, account_sid: str): """ Initialize the YearlyList - :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.record.yearly.YearlyList - :rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList """ - super(YearlyList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Usage/Records/Yearly.json'.format(**self._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): + def stream( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[YearlyInstance]: """ Streams YearlyInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param YearlyInstance.Category category: The usage category 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) + :param str 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 - :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'], + page_size=limits["page_size"], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + return self._version.stream(page, limits["limit"]) - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=values.unset, limit=None, - page_size=None): + async def stream_async( + self, + category: Union[str, 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]: """ - Lists YearlyInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + 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 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) + :param str 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 - :rtype: list[twilio.rest.api.v2010.account.usage.record.yearly.YearlyInstance] """ - return list(self.stream( + 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, - 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 + page_size=limits["page_size"], + ) - :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 + return self._version.stream_async(page, limits["limit"]) - :returns: Page of YearlyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyPage + def stream_with_http_info( + self, + category: Union[str, 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, + ) -> tuple: """ - 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, - }) + Streams YearlyInstance and returns headers from first page - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return YearlyPage(self._version, response, self._solution) + :param str 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) - def get_page(self, target_url): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - 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, + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], ) - return YearlyPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: Machine friendly representation - :rtype: str + async def stream_with_http_info_async( + self, + category: Union[str, 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, + ) -> tuple: """ - return '' + Asynchronously streams YearlyInstance and returns headers from first page -class YearlyPage(Page): - """ """ + :param str 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) - def __init__(self, version, response, solution): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Initialize the YearlyPage + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) - :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. + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: twilio.rest.api.v2010.account.usage.record.yearly.YearlyPage - :rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyPage + def list( + self, + category: Union[str, 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]: """ - super(YearlyPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + Lists YearlyInstance 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): - """ - Build an instance of YearlyInstance + :param str 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, + ) + ) - :param dict payload: Payload response from the API + async def list_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[YearlyInstance]: + """ + Asynchronously lists YearlyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: twilio.rest.api.v2010.account.usage.record.yearly.YearlyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyInstance + :param str 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 list_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Lists YearlyInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously lists YearlyInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + category: Union[str, 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: """ - return YearlyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Retrieve a single page of YearlyInstance records from the API. + Request is executed immediately - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Page of YearlyInstance """ - return '' + 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"}) -class YearlyInstance(InstanceResource): - """ """ - - class Category(object): - AGENT_CONFERENCE = "agent-conference" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - 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_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" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IP_MESSAGING = "ip-messaging" - IP_MESSAGING_COMMANDS = "ip-messaging-commands" - IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" - IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" - IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = "marketplace-algorithmia-named-entity-recognition" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = "marketplace-ibm-watson-message-insights" - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = "marketplace-ibm-watson-message-sentiment" - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = "marketplace-ibm-watson-recording-analysis" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" - MARKETPLACE_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_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = "marketplace-twilio-caller-name-lookup-us" - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = "marketplace-twilio-carrier-information-lookup" - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = "marketplace-whitepages-pro-caller-identification" - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = "marketplace-whitepages-pro-phone-intelligence" - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = "marketplace-whitepages-pro-phone-reputation" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_ACTIONS = "pchat-actions" - PCHAT_APS = "pchat-aps" - PCHAT_NOTIFICATIONS = "pchat-notifications" - PCHAT_READS = "pchat-reads" - PCHAT_USERS = "pchat-users" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VIDEO_RECORDINGS = "video-recordings" - 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" - WIRELESS = "wireless" - 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_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = "wireless-usage-commands-centralandsouthamerica" - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = "wireless-usage-data-centralandsouthamerica" - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = "wireless-usage-data-custom-additionalmb" - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = "wireless-usage-data-individual-additionalgb" - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = "wireless-usage-data-individual-firstgb" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = "wireless-usage-data-international-roaming-canada" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = "wireless-usage-data-international-roaming-india" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = "wireless-usage-data-international-roaming-mexico" - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - - def __init__(self, version, payload, account_sid): - """ - Initialize the YearlyInstance - - :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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return YearlyPage(self._version, response, solution=self._solution) + + async def page_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> YearlyPage: + """ + Asynchronously retrieve a single page of YearlyInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + :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 - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + :returns: Page of YearlyInstance """ - return self._properties['api_version'] + 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 as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode - """ - return self._properties['as_of'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def category(self): - """ - :returns: The category of usage - :rtype: YearlyInstance.Category - """ - return self._properties['category'] + headers["Accept"] = "application/json" - @property - def count(self): - """ - :returns: The number of usage events - :rtype: unicode - """ - return self._properties['count'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return YearlyPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with YearlyPage, status code, and headers + """ + 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 count_unit(self): - """ - :returns: The units in which count is measured - :rtype: unicode - """ - return self._properties['count_unit'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def description(self): - """ - :returns: A plain-language description of the usage category - :rtype: unicode - """ - return self._properties['description'] + headers["Accept"] = "application/json" - @property - def end_date(self): - """ - :returns: The last date for which usage is included in the UsageRecord - :rtype: date - """ - return self._properties['end_date'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = YearlyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with YearlyPage, status code, and headers + """ + 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 price(self): - """ - :returns: The total price of the usage - :rtype: unicode - """ - return self._properties['price'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def price_unit(self): - """ - :returns: The currency in which `price` is measured - :rtype: unicode - """ - return self._properties['price_unit'] + headers["Accept"] = "application/json" - @property - def start_date(self): - """ - :returns: The first date for which usage is included in this UsageRecord - :rtype: date - """ - return self._properties['start_date'] + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = YearlyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def subresource_uris(self): + def get_page(self, target_url: str) -> YearlyPage: """ - :returns: A list of related resources identified by their relative URIs - :rtype: unicode - """ - return self._properties['subresource_uris'] + Retrieve a specific page of YearlyInstance 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 target_url: API-generated URL for the requested results page - @property - def usage(self): - """ - :returns: The amount of usage - :rtype: unicode + :returns: Page of YearlyInstance """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return YearlyPage(self._version, response, solution=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, solution=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 a72050e304..32ad22f8d0 100644 --- a/twilio/rest/api/v2010/account/usage/record/yesterday.py +++ b/twilio/rest/api/v2010/account/usage/record/yesterday.py @@ -1,611 +1,647 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class YesterdayInstance(InstanceResource): + """ + :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: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :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[str] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class YesterdayPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> YesterdayInstance: + """ + Build an instance of YesterdayInstance + + :param payload: Payload response from the API + """ + + return YesterdayInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class YesterdayList(ListResource): - """ """ - def __init__(self, version, account_sid): + def __init__(self, version: Version, account_sid: str): """ Initialize the YesterdayList - :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.record.yesterday.YesterdayList - :rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayList """ - super(YesterdayList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Usage/Records/Yesterday.json'.format(**self._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): + def stream( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[YesterdayInstance]: """ Streams YesterdayInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param YesterdayInstance.Category category: The usage category 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) + :param str 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 - :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'], + page_size=limits["page_size"], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + return self._version.stream(page, limits["limit"]) - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=values.unset, limit=None, - page_size=None): + async def stream_async( + self, + category: Union[str, 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]: """ - Lists YesterdayInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + 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 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) + :param str 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 - :rtype: list[twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayInstance] """ - return list(self.stream( + 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, - 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 + page_size=limits["page_size"], + ) - :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 + return self._version.stream_async(page, limits["limit"]) - :returns: Page of YesterdayInstance - :rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayPage + def stream_with_http_info( + self, + category: Union[str, 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, + ) -> tuple: """ - 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, - }) + Streams YesterdayInstance and returns headers from first page - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return YesterdayPage(self._version, response, self._solution) + :param str 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) - def get_page(self, target_url): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - 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, + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], ) - return YesterdayPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: Machine friendly representation - :rtype: str + async def stream_with_http_info_async( + self, + category: Union[str, 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, + ) -> tuple: """ - return '' + Asynchronously streams YesterdayInstance and returns headers from first page -class YesterdayPage(Page): - """ """ + :param str 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) - def __init__(self, version, response, solution): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Initialize the YesterdayPage + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) - :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. + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayPage - :rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayPage + def list( + self, + category: Union[str, 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]: """ - super(YesterdayPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + Lists YesterdayInstance 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): - """ - Build an instance of YesterdayInstance + :param str 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, + ) + ) - :param dict payload: Payload response from the API + async def list_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[YesterdayInstance]: + """ + Asynchronously lists YesterdayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayInstance - :rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayInstance + :param str 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 list_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Lists YesterdayInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously lists YesterdayInstance and returns headers from first page + + + :param str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + category: Union[str, 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: """ - return YesterdayInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Retrieve a single page of YesterdayInstance records from the API. + Request is executed immediately - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Page of YesterdayInstance """ - return '' + 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"}) -class YesterdayInstance(InstanceResource): - """ """ - - class Category(object): - AGENT_CONFERENCE = "agent-conference" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - 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_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" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IP_MESSAGING = "ip-messaging" - IP_MESSAGING_COMMANDS = "ip-messaging-commands" - IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" - IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" - IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = "marketplace-algorithmia-named-entity-recognition" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = "marketplace-ibm-watson-message-insights" - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = "marketplace-ibm-watson-message-sentiment" - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = "marketplace-ibm-watson-recording-analysis" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" - MARKETPLACE_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_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = "marketplace-twilio-caller-name-lookup-us" - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = "marketplace-twilio-carrier-information-lookup" - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = "marketplace-whitepages-pro-caller-identification" - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = "marketplace-whitepages-pro-phone-intelligence" - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = "marketplace-whitepages-pro-phone-reputation" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_ACTIONS = "pchat-actions" - PCHAT_APS = "pchat-aps" - PCHAT_NOTIFICATIONS = "pchat-notifications" - PCHAT_READS = "pchat-reads" - PCHAT_USERS = "pchat-users" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VIDEO_RECORDINGS = "video-recordings" - 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" - WIRELESS = "wireless" - 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_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = "wireless-usage-commands-centralandsouthamerica" - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = "wireless-usage-data-centralandsouthamerica" - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = "wireless-usage-data-custom-additionalmb" - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = "wireless-usage-data-individual-additionalgb" - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = "wireless-usage-data-individual-firstgb" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = "wireless-usage-data-international-roaming-canada" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = "wireless-usage-data-international-roaming-india" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = "wireless-usage-data-international-roaming-mexico" - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - - def __init__(self, version, payload, account_sid): - """ - Initialize the YesterdayInstance - - :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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return YesterdayPage(self._version, response, solution=self._solution) + + async def page_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> YesterdayPage: + """ + Asynchronously retrieve a single page of YesterdayInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + :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 - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + :returns: Page of YesterdayInstance """ - return self._properties['api_version'] + 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 as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode - """ - return self._properties['as_of'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def category(self): - """ - :returns: The category of usage - :rtype: YesterdayInstance.Category - """ - return self._properties['category'] + headers["Accept"] = "application/json" - @property - def count(self): - """ - :returns: The number of usage events - :rtype: unicode - """ - return self._properties['count'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return YesterdayPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with YesterdayPage, status code, and headers + """ + 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 count_unit(self): - """ - :returns: The units in which count is measured - :rtype: unicode - """ - return self._properties['count_unit'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def description(self): - """ - :returns: A plain-language description of the usage category - :rtype: unicode - """ - return self._properties['description'] + headers["Accept"] = "application/json" - @property - def end_date(self): - """ - :returns: The last date for which usage is included in the UsageRecord - :rtype: date - """ - return self._properties['end_date'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = YesterdayPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, 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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with YesterdayPage, status code, and headers + """ + 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 price(self): - """ - :returns: The total price of the usage - :rtype: unicode - """ - return self._properties['price'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def price_unit(self): - """ - :returns: The currency in which `price` is measured - :rtype: unicode - """ - return self._properties['price_unit'] + headers["Accept"] = "application/json" - @property - def start_date(self): - """ - :returns: The first date for which usage is included in this UsageRecord - :rtype: date - """ - return self._properties['start_date'] + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = YesterdayPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def subresource_uris(self): + def get_page(self, target_url: str) -> YesterdayPage: """ - :returns: A list of related resources identified by their relative URIs - :rtype: unicode - """ - return self._properties['subresource_uris'] + Retrieve a specific page of YesterdayInstance 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 target_url: API-generated URL for the requested results page - @property - def usage(self): - """ - :returns: The amount of usage - :rtype: unicode + :returns: Page of YesterdayInstance """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return YesterdayPage(self._version, response, solution=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, solution=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 2e8728db71..8e975e0204 100644 --- a/twilio/rest/api/v2010/account/usage/trigger.py +++ b/twilio/rest/api/v2010/account/usage/trigger.py @@ -1,812 +1,1413 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +class TriggerInstance(InstanceResource): + + class Recurring(object): + DAILY = "daily" + MONTHLY = "monthly" + YEARLY = "yearly" + ALLTIME = "alltime" + + class TriggerField(object): + COUNT = "count" + USAGE = "usage" + PRICE = "price" - def __init__(self, version, account_sid): + """ + :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: The usage category the trigger watches. Must be one of the supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :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[str] = payload.get("usage_category") + self.usage_record_uri: Optional[str] = payload.get("usage_record_uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + + self._context: Optional[TriggerContext] = None + + @property + def _proxy(self) -> "TriggerContext": """ - Initialize the TriggerList + 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: TriggerContext for this TriggerInstance + """ + if self._context is None: + self._context = TriggerContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerList - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerList + def delete(self) -> bool: """ - super(TriggerList, self).__init__(version) + Deletes the TriggerInstance - # 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): + :returns: True if delete succeeds, False otherwise """ - Create the TriggerInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TriggerInstance - :returns: The created TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'CallbackUrl': callback_url, - 'TriggerValue': trigger_value, - 'UsageCategory': usage_category, - 'CallbackMethod': callback_method, - 'FriendlyName': friendly_name, - 'Recurring': recurring, - 'TriggerBy': trigger_by, - }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TriggerInstance with HTTP info - 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): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :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) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TriggerInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.trigger.TriggerInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page( - recurring=recurring, - trigger_by=trigger_by, - usage_category=usage_category, - page_size=limits['page_size'], - ) + def fetch(self) -> "TriggerInstance": + """ + Fetch the TriggerInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, recurring=values.unset, trigger_by=values.unset, - usage_category=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() - :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) + async def fetch_async(self) -> "TriggerInstance": + """ + Asynchronous coroutine to fetch the TriggerInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.trigger.TriggerInstance] + + :returns: The fetched TriggerInstance """ - return list(self.stream( - recurring=recurring, - trigger_by=trigger_by, - usage_category=usage_category, - limit=limit, - page_size=page_size, - )) + return await self._proxy.fetch_async() - 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of TriggerInstance records from the API. - Request is executed immediately + Fetch the TriggerInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Recurring': recurring, - 'TriggerBy': trigger_by, - 'UsageCategory': usage_category, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TriggerInstance with HTTP info - return TriggerPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of TriggerInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "TriggerInstance": + """ + Update the TriggerInstance - :returns: Page of TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerPage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, ) - return TriggerPage(self._version, response, self._solution) + async def update_async( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "TriggerInstance": + """ + Asynchronous coroutine to update the TriggerInstance - def get(self, sid): + :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 """ - Constructs a TriggerContext + return await self._proxy.update_async( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) - :param sid: The unique string that identifies the resource + def update_with_http_info( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the TriggerInstance with HTTP info + + :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: twilio.rest.api.v2010.account.usage.trigger.TriggerContext - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerContext + :returns: ApiResponse with instance, status code, and headers """ - return TriggerContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Constructs a TriggerContext + Asynchronous coroutine to update the TriggerInstance with HTTP info - :param sid: The unique string that identifies the resource + :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: twilio.rest.api.v2010.account.usage.trigger.TriggerContext - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerContext + :returns: ApiResponse with instance, status code, and headers """ - return TriggerContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + callback_method=callback_method, + callback_url=callback_url, + 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 TriggerPage(Page): - """ """ +class TriggerContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - 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. + Initialize the TriggerContext - :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerPage - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerPage + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageTrigger resources to update. + :param sid: The Twilio-provided string that uniquely identifies the UsageTrigger resource to update. """ - super(TriggerPage, 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}/Usage/Triggers/{sid}.json".format( + **self._solution + ) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of TriggerInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return TriggerInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Deletes the TriggerInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the TriggerInstance and return response metadata -class TriggerContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, account_sid, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - 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 + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerContext - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(TriggerContext, self).__init__(version) + Asynchronous coroutine that deletes the TriggerInstance - # 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): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TriggerInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TriggerInstance: """ 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, ) - + payload, _, _ = self._fetch() return TriggerInstance( 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, callback_method=values.unset, callback_url=values.unset, - friendly_name=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Update the TriggerInstance + Fetch the TriggerInstance and return response metadata - :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 + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TriggerInstance: """ - data = values.of({ - 'CallbackMethod': callback_method, - 'CallbackUrl': callback_url, - 'FriendlyName': friendly_name, - }) + Asynchronous coroutine to fetch the TriggerInstance - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :returns: The fetched TriggerInstance + """ + payload, _, _ = await self._fetch_async() return TriggerInstance( 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 fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the TriggerInstance + Asynchronous coroutine to fetch the TriggerInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(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, + ) -> tuple: """ - Provide a friendly representation + Internal helper for update operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) -class TriggerInstance(InstanceResource): - """ """ - - class UsageCategory(object): - AGENT_CONFERENCE = "agent-conference" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - 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_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" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - FRAUD_LOOKUPS = "fraud-lookups" - CPS = "cps" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IP_MESSAGING = "ip-messaging" - IP_MESSAGING_COMMANDS = "ip-messaging-commands" - IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" - IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" - IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = "marketplace-algorithmia-named-entity-recognition" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = "marketplace-ibm-watson-message-insights" - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = "marketplace-ibm-watson-message-sentiment" - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = "marketplace-ibm-watson-recording-analysis" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" - MARKETPLACE_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_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = "marketplace-twilio-caller-name-lookup-us" - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = "marketplace-twilio-carrier-information-lookup" - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = "marketplace-whitepages-pro-caller-identification" - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = "marketplace-whitepages-pro-phone-intelligence" - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = "marketplace-whitepages-pro-phone-reputation" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_ACTIONS = "pchat-actions" - PCHAT_APS = "pchat-aps" - PCHAT_NOTIFICATIONS = "pchat-notifications" - PCHAT_READS = "pchat-reads" - PCHAT_USERS = "pchat-users" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VIDEO_RECORDINGS = "video-recordings" - 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" - WIRELESS = "wireless" - 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_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = "wireless-usage-commands-centralandsouthamerica" - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = "wireless-usage-data-centralandsouthamerica" - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = "wireless-usage-data-custom-additionalmb" - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = "wireless-usage-data-individual-additionalgb" - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = "wireless-usage-data-individual-firstgb" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = "wireless-usage-data-international-roaming-canada" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = "wireless-usage-data-international-roaming-india" - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = "wireless-usage-data-international-roaming-mexico" - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - WIRELESS_USAGE_SMS = "wireless-usage-sms" + headers["Content-Type"] = "application/x-www-form-urlencoded" - class Recurring(object): - DAILY = "daily" - MONTHLY = "monthly" - YEARLY = "yearly" - ALLTIME = "alltime" + headers["Accept"] = "application/json" - class TriggerField(object): - COUNT = "count" - USAGE = "usage" - PRICE = "price" + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - 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'), - } + def update( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> TriggerInstance: + """ + Update the TriggerInstance - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + :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. - @property - def _proxy(self): + :returns: The updated TriggerInstance """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, _, _ = self._update( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) + return TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - :returns: TriggerContext for this TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerContext + def update_with_http_info( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: """ - if self._context is None: - self._context = TriggerContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + Update the TriggerInstance and return response metadata - @property - def account_sid(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: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Account that this trigger monitors - :rtype: unicode + payload, status_code, headers = self._update( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) + instance = TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for update operation - @property - def api_version(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The API version used to create the resource - :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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['api_version'] + Asynchronous coroutine to update the TriggerInstance - @property - def callback_method(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 + """ + payload, _, _ = await self._update_async( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) + return TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: """ - :returns: The HTTP method we use to call callback_url - :rtype: unicode + Asynchronous coroutine to update the TriggerInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['callback_method'] + payload, status_code, headers = await self._update_async( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) + instance = TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def callback_url(self): + def __repr__(self) -> str: """ - :returns: he URL we call when the trigger fires - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['callback_url'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def current_value(self): + +class TriggerPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TriggerInstance: """ - :returns: The current value of the field the trigger is watching - :rtype: unicode + Build an instance of TriggerInstance + + :param payload: Payload response from the API """ - return self._properties['current_value'] - @property - def date_created(self): + return TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['date_created'] + return "" - @property - def date_fired(self): + +class TriggerList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - :returns: The RFC 2822 date and time in GMT that the trigger was last fired - :rtype: datetime + 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. + """ - return self._properties['date_fired'] + super().__init__(version) - @property - def date_updated(self): + # 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: str, + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + callback_url: str, + trigger_value: str, + usage_category: str, + 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: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + 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: The usage category that the trigger should watch. Use one of the supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) for this value. + :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 """ - return self._properties['date_updated'] + payload, _, _ = self._create( + callback_url=callback_url, + trigger_value=trigger_value, + usage_category=usage_category, + callback_method=callback_method, + friendly_name=friendly_name, + recurring=recurring, + trigger_by=trigger_by, + ) + return TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def friendly_name(self): + def create_with_http_info( + self, + callback_url: str, + trigger_value: str, + usage_category: str, + 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, + ) -> ApiResponse: + """ + Create the TriggerInstance and return response metadata + + :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: The usage category that the trigger should watch. Use one of the supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) for this value. + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + callback_url=callback_url, + trigger_value=trigger_value, + usage_category=usage_category, + callback_method=callback_method, + friendly_name=friendly_name, + recurring=recurring, + trigger_by=trigger_by, + ) + instance = TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + callback_url: str, + trigger_value: str, + usage_category: str, + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + callback_url: str, + trigger_value: str, + usage_category: str, + 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: The usage category that the trigger should watch. Use one of the supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) for this value. + :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 """ - :returns: The string that you assigned to describe the trigger - :rtype: unicode + payload, _, _ = await self._create_async( + callback_url=callback_url, + trigger_value=trigger_value, + usage_category=usage_category, + callback_method=callback_method, + friendly_name=friendly_name, + recurring=recurring, + trigger_by=trigger_by, + ) + return TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_with_http_info_async( + self, + callback_url: str, + trigger_value: str, + usage_category: str, + 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, + ) -> ApiResponse: + """ + Asynchronously create the TriggerInstance and return response metadata + + :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: The usage category that the trigger should watch. Use one of the supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) for this value. + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + callback_url=callback_url, + trigger_value=trigger_value, + usage_category=usage_category, + callback_method=callback_method, + friendly_name=friendly_name, + recurring=recurring, + trigger_by=trigger_by, + ) + instance = TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TriggerInstance]: """ - return self._properties['friendly_name'] + Streams TriggerInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - @property - def recurring(self): + :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 str 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 """ - :returns: The frequency of a recurring UsageTrigger - :rtype: TriggerInstance.Recurring + 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[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TriggerInstance]: """ - return self._properties['recurring'] + 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. - @property - def sid(self): + :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 str 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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + 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 stream_with_http_info( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['sid'] + Streams TriggerInstance and returns headers from first page - @property - def trigger_by(self): + + :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 str 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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The field in the UsageRecord resource that fires the trigger - :rtype: TriggerInstance.TriggerField + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['trigger_by'] + Asynchronously streams TriggerInstance and returns headers from first page - @property - def trigger_value(self): + + :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 str 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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The value at which the trigger will fire - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TriggerInstance]: """ - return self._properties['trigger_value'] + Lists TriggerInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def uri(self): + :param "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 str 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[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TriggerInstance]: """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + 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 str 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 list_with_http_info( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['uri'] + Lists TriggerInstance and returns headers from first page - @property - def usage_category(self): + + :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 str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TriggerInstance and returns headers from first page + + + :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 str 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union[str, 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: """ - :returns: The usage category the trigger watches - :rtype: TriggerInstance.UsageCategory + 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 """ - return self._properties['usage_category'] + data = values.of( + { + "Recurring": recurring, + "TriggerBy": trigger_by, + "UsageCategory": usage_category, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def usage_record_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 TriggerPage(self._version, response, solution=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[str, 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 """ - :returns: The URI of the UsageRecord resource this trigger watches - :rtype: unicode + 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, solution=self._solution) + + def page_with_http_info( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with TriggerPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TriggerPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with TriggerPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TriggerPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> TriggerPage: """ - return self._properties['usage_record_uri'] + Retrieve a specific page of TriggerInstance 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 TriggerInstance """ - Fetch the TriggerInstance + response = self._version.domain.twilio.request("GET", target_url) + return TriggerPage(self._version, response, solution=self._solution) - :returns: The fetched TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance + async def get_page_async(self, target_url: str) -> TriggerPage: """ - return self._proxy.fetch() + 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 - def update(self, callback_method=values.unset, callback_url=values.unset, - friendly_name=values.unset): + :returns: Page of TriggerInstance """ - Update the TriggerInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return TriggerPage(self._version, response, solution=self._solution) - :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 + def get(self, sid: str) -> TriggerContext: + """ + Constructs a TriggerContext - :returns: The updated TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance + :param sid: The Twilio-provided string that uniquely identifies the UsageTrigger resource to update. """ - return self._proxy.update( - callback_method=callback_method, - callback_url=callback_url, - friendly_name=friendly_name, + return TriggerContext( + self._version, account_sid=self._solution["account_sid"], sid=sid ) - def delete(self): + def __call__(self, sid: str) -> TriggerContext: """ - Deletes the TriggerInstance + Constructs a TriggerContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the UsageTrigger resource to update. """ - return self._proxy.delete() + 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 994234caf3..9594e19cc1 100644 --- a/twilio/rest/api/v2010/account/validation_request.py +++ b/twilio/rest/api/v2010/account/validation_request.py @@ -1,186 +1,288 @@ -# 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, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource -from twilio.base.page import Page - - -class ValidationRequestList(ListResource): - """ """ +from twilio.base.version import Version - 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 - - :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, + ) -> tuple: """ - return ValidationRequestInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Internal helper for create operation - def __repr__(self): + Returns: + tuple: (payload, status_code, headers) """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 '' - + Create the ValidationRequestInstance -class ValidationRequestInstance(InstanceResource): - """ """ + :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`. - def __init__(self, version, payload, account_sid): + :returns: The created ValidationRequestInstance """ - Initialize the ValidationRequestInstance - - :returns: twilio.rest.api.v2010.account.validation_request.ValidationRequestInstance - :rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestInstance + payload, _, _ = self._create( + phone_number=phone_number, + friendly_name=friendly_name, + call_delay=call_delay, + extension=extension, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + return ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: """ - super(ValidationRequestInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'phone_number': payload.get('phone_number'), - 'friendly_name': payload.get('friendly_name'), - 'validation_code': deserialize.integer(payload.get('validation_code')), - 'call_sid': payload.get('call_sid'), - } + Create the ValidationRequestInstance and return response metadata - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + :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`. - @property - def account_sid(self): + :returns: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Account that created the resource - :rtype: unicode + payload, status_code, headers = self._create( + phone_number=phone_number, + friendly_name=friendly_name, + call_delay=call_delay, + extension=extension, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + instance = ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for create operation - @property - def phone_number(self): - """ - :returns: The phone number to verify in E.164 format - :rtype: unicode + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['phone_number'] - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._properties['friendly_name'] + Asynchronously create the ValidationRequestInstance - @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'] + :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`. - @property - def call_sid(self): + :returns: The created ValidationRequestInstance """ - :returns: The SID of the Call the resource is associated with - :rtype: unicode + payload, _, _ = await self._create_async( + phone_number=phone_number, + friendly_name=friendly_name, + call_delay=call_delay, + extension=extension, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + return ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['call_sid'] + Asynchronously create the ValidationRequestInstance and return response metadata - def __repr__(self): + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + friendly_name=friendly_name, + call_delay=call_delay, + extension=extension, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + instance = ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..aa3c171f63 --- /dev/null +++ b/twilio/rest/assistants/v1/assistant/__init__.py @@ -0,0 +1,1499 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssistantInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssistantInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssistantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssistantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the AssistantInstance with HTTP info + + :param assistants_v1_service_update_assistant_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request, + ) + + async def update_with_http_info_async( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AssistantInstance with HTTP info + + :param assistants_v1_service_update_assistant_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the AssistantInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssistantInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssistantInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AssistantInstance: + """ + Fetch the AssistantInstance + + + :returns: The fetched AssistantInstance + """ + payload, _, _ = self._fetch() + return AssistantInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssistantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AssistantInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AssistantInstance: + """ + Asynchronous coroutine to fetch the AssistantInstance + + + :returns: The fetched AssistantInstance + """ + payload, _, _ = await self._fetch_async() + return AssistantInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssistantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AssistantInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = assistants_v1_service_update_assistant_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request + ) + return AssistantInstance(self._version, payload, id=self._solution["id"]) + + def update_with_http_info( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the AssistantInstance and return response metadata + + :param assistants_v1_service_update_assistant_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request + ) + instance = AssistantInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = assistants_v1_service_update_assistant_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request + ) + return AssistantInstance(self._version, payload, id=self._solution["id"]) + + async def update_with_http_info_async( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AssistantInstance and return response metadata + + :param assistants_v1_service_update_assistant_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request + ) + instance = AssistantInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + assistants_v1_service_create_assistant_request=assistants_v1_service_create_assistant_request + ) + return AssistantInstance(self._version, payload) + + def create_with_http_info( + self, + assistants_v1_service_create_assistant_request: AssistantsV1ServiceCreateAssistantRequest, + ) -> ApiResponse: + """ + Create the AssistantInstance and return response metadata + + :param assistants_v1_service_create_assistant_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + assistants_v1_service_create_assistant_request=assistants_v1_service_create_assistant_request + ) + instance = AssistantInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + assistants_v1_service_create_assistant_request: AssistantsV1ServiceCreateAssistantRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + assistants_v1_service_create_assistant_request=assistants_v1_service_create_assistant_request + ) + return AssistantInstance(self._version, payload) + + async def create_with_http_info_async( + self, + assistants_v1_service_create_assistant_request: AssistantsV1ServiceCreateAssistantRequest, + ) -> ApiResponse: + """ + Asynchronously create the AssistantInstance and return response metadata + + :param assistants_v1_service_create_assistant_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + assistants_v1_service_create_assistant_request=assistants_v1_service_create_assistant_request + ) + instance = AssistantInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AssistantInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AssistantInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AssistantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AssistantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssistantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssistantPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssistantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssistantPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..e5d6ed5daa --- /dev/null +++ b/twilio/rest/assistants/v1/assistant/assistants_knowledge.py @@ -0,0 +1,871 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 create_with_http_info(self) -> ApiResponse: + """ + Create the AssistantsKnowledgeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info() + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the AssistantsKnowledgeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssistantsKnowledgeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssistantsKnowledgeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self) -> AssistantsKnowledgeInstance: + """ + Create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + payload, _, _ = self._create() + return AssistantsKnowledgeInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the AssistantsKnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = AssistantsKnowledgeInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self) -> AssistantsKnowledgeInstance: + """ + Asynchronous coroutine to create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + payload, _, _ = await self._create_async() + return AssistantsKnowledgeInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the AssistantsKnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = AssistantsKnowledgeInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the AssistantsKnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssistantsKnowledgeInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssistantsKnowledgeInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + return self._version.create_with_response_info( + method="POST", uri=self._uri, headers=headers + ) + + def create(self) -> AssistantsKnowledgeInstance: + """ + Create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + payload, _, _ = self._create() + return AssistantsKnowledgeInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the AssistantsKnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = AssistantsKnowledgeInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, headers=headers + ) + + async def create_async(self) -> AssistantsKnowledgeInstance: + """ + Asynchronously create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + payload, _, _ = await self._create_async() + return AssistantsKnowledgeInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the AssistantsKnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = AssistantsKnowledgeInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AssistantsKnowledgeInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AssistantsKnowledgeInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AssistantsKnowledgeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AssistantsKnowledgeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssistantsKnowledgePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssistantsKnowledgePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssistantsKnowledgePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssistantsKnowledgePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..eb7ab6b8c1 --- /dev/null +++ b/twilio/rest/assistants/v1/assistant/assistants_tool.py @@ -0,0 +1,869 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 create_with_http_info(self) -> ApiResponse: + """ + Create the AssistantsToolInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info() + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the AssistantsToolInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssistantsToolInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssistantsToolInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self) -> AssistantsToolInstance: + """ + Create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + payload, _, _ = self._create() + return AssistantsToolInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the AssistantsToolInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = AssistantsToolInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self) -> AssistantsToolInstance: + """ + Asynchronous coroutine to create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + payload, _, _ = await self._create_async() + return AssistantsToolInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the AssistantsToolInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = AssistantsToolInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the AssistantsToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssistantsToolInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssistantsToolInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + return self._version.create_with_response_info( + method="POST", uri=self._uri, headers=headers + ) + + def create(self) -> AssistantsToolInstance: + """ + Create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + payload, _, _ = self._create() + return AssistantsToolInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the AssistantsToolInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = AssistantsToolInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, headers=headers + ) + + async def create_async(self) -> AssistantsToolInstance: + """ + Asynchronously create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + payload, _, _ = await self._create_async() + return AssistantsToolInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the AssistantsToolInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = AssistantsToolInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AssistantsToolInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AssistantsToolInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AssistantsToolInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AssistantsToolInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssistantsToolPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssistantsToolPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssistantsToolPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssistantsToolPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..b52770b788 --- /dev/null +++ b/twilio/rest/assistants/v1/assistant/feedback.py @@ -0,0 +1,638 @@ +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.api_response import ApiResponse + +from twilio.base.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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + assistants_v1_service_create_feedback_request=assistants_v1_service_create_feedback_request + ) + return FeedbackInstance(self._version, payload, id=self._solution["id"]) + + def create_with_http_info( + self, + assistants_v1_service_create_feedback_request: AssistantsV1ServiceCreateFeedbackRequest, + ) -> ApiResponse: + """ + Create the FeedbackInstance and return response metadata + + :param assistants_v1_service_create_feedback_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + assistants_v1_service_create_feedback_request=assistants_v1_service_create_feedback_request + ) + instance = FeedbackInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + assistants_v1_service_create_feedback_request: AssistantsV1ServiceCreateFeedbackRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + assistants_v1_service_create_feedback_request=assistants_v1_service_create_feedback_request + ) + return FeedbackInstance(self._version, payload, id=self._solution["id"]) + + async def create_with_http_info_async( + self, + assistants_v1_service_create_feedback_request: AssistantsV1ServiceCreateFeedbackRequest, + ) -> ApiResponse: + """ + Asynchronously create the FeedbackInstance and return response metadata + + :param assistants_v1_service_create_feedback_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + assistants_v1_service_create_feedback_request=assistants_v1_service_create_feedback_request + ) + instance = FeedbackInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams FeedbackInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams FeedbackInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists FeedbackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists FeedbackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FeedbackPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FeedbackPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FeedbackPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FeedbackPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..38adca4cec --- /dev/null +++ b/twilio/rest/assistants/v1/assistant/message.py @@ -0,0 +1,247 @@ +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.api_response import ApiResponse + +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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + assistants_v1_service_assistant_send_message_request=assistants_v1_service_assistant_send_message_request + ) + return MessageInstance(self._version, payload, id=self._solution["id"]) + + def create_with_http_info( + self, + assistants_v1_service_assistant_send_message_request: AssistantsV1ServiceAssistantSendMessageRequest, + ) -> ApiResponse: + """ + Create the MessageInstance and return response metadata + + :param assistants_v1_service_assistant_send_message_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + assistants_v1_service_assistant_send_message_request=assistants_v1_service_assistant_send_message_request + ) + instance = MessageInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + assistants_v1_service_assistant_send_message_request: AssistantsV1ServiceAssistantSendMessageRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + assistants_v1_service_assistant_send_message_request=assistants_v1_service_assistant_send_message_request + ) + return MessageInstance(self._version, payload, id=self._solution["id"]) + + async def create_with_http_info_async( + self, + assistants_v1_service_assistant_send_message_request: AssistantsV1ServiceAssistantSendMessageRequest, + ) -> ApiResponse: + """ + Asynchronously create the MessageInstance and return response metadata + + :param assistants_v1_service_assistant_send_message_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + assistants_v1_service_assistant_send_message_request=assistants_v1_service_assistant_send_message_request + ) + instance = MessageInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..e31a496d94 --- /dev/null +++ b/twilio/rest/assistants/v1/knowledge/__init__.py @@ -0,0 +1,1443 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeInstance with HTTP info + + :param assistants_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + assistants_v1_service_update_knowledge_request=assistants_v1_service_update_knowledge_request, + ) + + async def update_with_http_info_async( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeInstance with HTTP info + + :param assistants_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the KnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> KnowledgeInstance: + """ + Fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + payload, _, _ = self._fetch() + return KnowledgeInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = KnowledgeInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> KnowledgeInstance: + """ + Asynchronous coroutine to fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + payload, _, _ = await self._fetch_async() + return KnowledgeInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = KnowledgeInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = assistants_v1_service_update_knowledge_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + assistants_v1_service_update_knowledge_request=assistants_v1_service_update_knowledge_request + ) + return KnowledgeInstance(self._version, payload, id=self._solution["id"]) + + def update_with_http_info( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeInstance and return response metadata + + :param assistants_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + assistants_v1_service_update_knowledge_request=assistants_v1_service_update_knowledge_request + ) + instance = KnowledgeInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = assistants_v1_service_update_knowledge_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + assistants_v1_service_update_knowledge_request=assistants_v1_service_update_knowledge_request + ) + return KnowledgeInstance(self._version, payload, id=self._solution["id"]) + + async def update_with_http_info_async( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeInstance and return response metadata + + :param assistants_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + assistants_v1_service_update_knowledge_request=assistants_v1_service_update_knowledge_request + ) + instance = KnowledgeInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + assistants_v1_service_create_knowledge_request=assistants_v1_service_create_knowledge_request + ) + return KnowledgeInstance(self._version, payload) + + def create_with_http_info( + self, + assistants_v1_service_create_knowledge_request: AssistantsV1ServiceCreateKnowledgeRequest, + ) -> ApiResponse: + """ + Create the KnowledgeInstance and return response metadata + + :param assistants_v1_service_create_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + assistants_v1_service_create_knowledge_request=assistants_v1_service_create_knowledge_request + ) + instance = KnowledgeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + assistants_v1_service_create_knowledge_request: AssistantsV1ServiceCreateKnowledgeRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + assistants_v1_service_create_knowledge_request=assistants_v1_service_create_knowledge_request + ) + return KnowledgeInstance(self._version, payload) + + async def create_with_http_info_async( + self, + assistants_v1_service_create_knowledge_request: AssistantsV1ServiceCreateKnowledgeRequest, + ) -> ApiResponse: + """ + Asynchronously create the KnowledgeInstance and return response metadata + + :param assistants_v1_service_create_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + assistants_v1_service_create_knowledge_request=assistants_v1_service_create_knowledge_request + ) + instance = KnowledgeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams KnowledgeInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + assistant_id=assistant_id, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams KnowledgeInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + assistant_id=assistant_id, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists KnowledgeInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + assistant_id=assistant_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists KnowledgeInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + assistant_id=assistant_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with KnowledgePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = KnowledgePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with KnowledgePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = KnowledgePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..fba901e7d1 --- /dev/null +++ b/twilio/rest/assistants/v1/knowledge/chunk.py @@ -0,0 +1,471 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChunkInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChunkInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChunkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChunkPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChunkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChunkPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..a6881230e3 --- /dev/null +++ b/twilio/rest/assistants/v1/knowledge/knowledge_status.py @@ -0,0 +1,264 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> KnowledgeStatusInstance: + """ + Fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + payload, _, _ = self._fetch() + return KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeStatusInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> KnowledgeStatusInstance: + """ + Asynchronous coroutine to fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + payload, _, _ = await self._fetch_async() + return KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeStatusInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..37d5bb1def --- /dev/null +++ b/twilio/rest/assistants/v1/policy.py @@ -0,0 +1,540 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PolicyInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + tool_id=tool_id, knowledge_id=knowledge_id, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams PolicyInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + tool_id=tool_id, knowledge_id=knowledge_id, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PolicyInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + tool_id=tool_id, + knowledge_id=knowledge_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists PolicyInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + tool_id=tool_id, + knowledge_id=knowledge_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with PolicyPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PolicyPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with PolicyPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PolicyPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..26b17a103c --- /dev/null +++ b/twilio/rest/assistants/v1/session/__init__.py @@ -0,0 +1,680 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SessionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SessionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SessionInstance: + """ + Fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + payload, _, _ = self._fetch() + return SessionInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SessionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SessionInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SessionInstance: + """ + Asynchronous coroutine to fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + payload, _, _ = await self._fetch_async() + return SessionInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SessionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SessionInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SessionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SessionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SessionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SessionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SessionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SessionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..f8fba1fbde --- /dev/null +++ b/twilio/rest/assistants/v1/session/message.py @@ -0,0 +1,483 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MessageInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MessageInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MessageInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MessageInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..13f2c71aaa --- /dev/null +++ b/twilio/rest/assistants/v1/tool.py @@ -0,0 +1,1397 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ToolInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ToolInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ToolInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ToolInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ToolInstance with HTTP info + + :param assistants_v1_service_update_tool_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request, + ) + + async def update_with_http_info_async( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ToolInstance with HTTP info + + :param assistants_v1_service_update_tool_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ToolInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ToolInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ToolInstance: + """ + Fetch the ToolInstance + + + :returns: The fetched ToolInstance + """ + payload, _, _ = self._fetch() + return ToolInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ToolInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ToolInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ToolInstance: + """ + Asynchronous coroutine to fetch the ToolInstance + + + :returns: The fetched ToolInstance + """ + payload, _, _ = await self._fetch_async() + return ToolInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ToolInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ToolInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = assistants_v1_service_update_tool_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request + ) + return ToolInstance(self._version, payload, id=self._solution["id"]) + + def update_with_http_info( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ToolInstance and return response metadata + + :param assistants_v1_service_update_tool_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request + ) + instance = ToolInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = assistants_v1_service_update_tool_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request + ) + return ToolInstance(self._version, payload, id=self._solution["id"]) + + async def update_with_http_info_async( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ToolInstance and return response metadata + + :param assistants_v1_service_update_tool_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request + ) + instance = ToolInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + assistants_v1_service_create_tool_request=assistants_v1_service_create_tool_request + ) + return ToolInstance(self._version, payload) + + def create_with_http_info( + self, + assistants_v1_service_create_tool_request: AssistantsV1ServiceCreateToolRequest, + ) -> ApiResponse: + """ + Create the ToolInstance and return response metadata + + :param assistants_v1_service_create_tool_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + assistants_v1_service_create_tool_request=assistants_v1_service_create_tool_request + ) + instance = ToolInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + assistants_v1_service_create_tool_request: AssistantsV1ServiceCreateToolRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + assistants_v1_service_create_tool_request=assistants_v1_service_create_tool_request + ) + return ToolInstance(self._version, payload) + + async def create_with_http_info_async( + self, + assistants_v1_service_create_tool_request: AssistantsV1ServiceCreateToolRequest, + ) -> ApiResponse: + """ + Asynchronously create the ToolInstance and return response metadata + + :param assistants_v1_service_create_tool_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + assistants_v1_service_create_tool_request=assistants_v1_service_create_tool_request + ) + instance = ToolInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ToolInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + assistant_id=assistant_id, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ToolInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + assistant_id=assistant_id, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ToolInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + assistant_id=assistant_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ToolInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + assistant_id=assistant_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ToolPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ToolPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ToolPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ToolPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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/authy/__init__.py b/twilio/rest/authy/__init__.py deleted file mode 100644 index 8273d61417..0000000000 --- a/twilio/rest/authy/__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.authy.v1 import V1 - - -class Authy(Domain): - - def __init__(self, twilio): - """ - Initialize the Authy Domain - - :returns: Domain for Authy - :rtype: twilio.rest.authy.Authy - """ - super(Authy, self).__init__(twilio) - - self.base_url = 'https://authy.twilio.com' - - # Versions - self._v1 = None - - @property - def v1(self): - """ - :returns: Version v1 of authy - :rtype: twilio.rest.authy.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 - - @property - def forms(self): - """ - :rtype: twilio.rest.authy.v1.form.FormList - """ - return self.v1.forms - - @property - def services(self): - """ - :rtype: twilio.rest.authy.v1.service.ServiceList - """ - return self.v1.services - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/authy/v1/__init__.py b/twilio/rest/authy/v1/__init__.py deleted file mode 100644 index 8a43e91001..0000000000 --- a/twilio/rest/authy/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.authy.v1.form import FormList -from twilio.rest.authy.v1.service import ServiceList - - -class V1(Version): - - def __init__(self, domain): - """ - Initialize the V1 version of Authy - - :returns: V1 version of Authy - :rtype: twilio.rest.authy.v1.V1.V1 - """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._forms = None - self._services = None - - @property - def forms(self): - """ - :rtype: twilio.rest.authy.v1.form.FormList - """ - if self._forms is None: - self._forms = FormList(self) - return self._forms - - @property - def services(self): - """ - :rtype: twilio.rest.authy.v1.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/authy/v1/form.py b/twilio/rest/authy/v1/form.py deleted file mode 100644 index 5ac9fc3fdb..0000000000 --- a/twilio/rest/authy/v1/form.py +++ /dev/null @@ -1,244 +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 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. """ - - def __init__(self, version): - """ - Initialize the FormList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.authy.v1.form.FormList - :rtype: twilio.rest.authy.v1.form.FormList - """ - super(FormList, self).__init__(version) - - # Path Solution - self._solution = {} - - def get(self, form_type): - """ - Constructs a FormContext - - :param form_type: The Type of this Form - - :returns: twilio.rest.authy.v1.form.FormContext - :rtype: twilio.rest.authy.v1.form.FormContext - """ - return FormContext(self._version, form_type=form_type, ) - - def __call__(self, form_type): - """ - Constructs a FormContext - - :param form_type: The Type of this Form - - :returns: twilio.rest.authy.v1.form.FormContext - :rtype: twilio.rest.authy.v1.form.FormContext - """ - return FormContext(self._version, form_type=form_type, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -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. """ - - def __init__(self, version, response, solution): - """ - Initialize the FormPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.authy.v1.form.FormPage - :rtype: twilio.rest.authy.v1.form.FormPage - """ - super(FormPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of FormInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.authy.v1.form.FormInstance - :rtype: twilio.rest.authy.v1.form.FormInstance - """ - return FormInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -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. """ - - def __init__(self, version, form_type): - """ - Initialize the FormContext - - :param Version version: Version that contains the resource - :param form_type: The Type of this Form - - :returns: twilio.rest.authy.v1.form.FormContext - :rtype: twilio.rest.authy.v1.form.FormContext - """ - super(FormContext, self).__init__(version) - - # Path Solution - self._solution = {'form_type': form_type, } - self._uri = '/Forms/{form_type}'.format(**self._solution) - - def fetch(self): - """ - Fetch the FormInstance - - :returns: The fetched FormInstance - :rtype: twilio.rest.authy.v1.form.FormInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return FormInstance(self._version, payload, form_type=self._solution['form_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 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. """ - - class FormTypes(object): - FORM_APP_PUSH = "form-app-push" - FORM_SMS = "form-sms" - FORM_TOTP = "form-totp" - - def __init__(self, version, payload, form_type=None): - """ - Initialize the FormInstance - - :returns: twilio.rest.authy.v1.form.FormInstance - :rtype: twilio.rest.authy.v1.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'], } - - @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: FormContext for this FormInstance - :rtype: twilio.rest.authy.v1.form.FormContext - """ - if self._context is None: - self._context = FormContext(self._version, form_type=self._solution['form_type'], ) - return self._context - - @property - def form_type(self): - """ - :returns: The Type of this Form - :rtype: FormInstance.FormTypes - """ - return self._properties['form_type'] - - @property - def forms(self): - """ - :returns: Object that contains the available forms for this type. - :rtype: dict - """ - return self._properties['forms'] - - @property - def form_meta(self): - """ - :returns: Additional information for the available forms for this type. - :rtype: dict - """ - return self._properties['form_meta'] - - @property - def url(self): - """ - :returns: The URL to access the forms for this type. - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the FormInstance - - :returns: The fetched FormInstance - :rtype: twilio.rest.authy.v1.form.FormInstance - """ - 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/authy/v1/service/__init__.py b/twilio/rest/authy/v1/service/__init__.py deleted file mode 100644 index d7fe12914f..0000000000 --- a/twilio/rest/authy/v1/service/__init__.py +++ /dev/null @@ -1,476 +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.authy.v1.service.entity import EntityList - - -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.authy.v1.service.ServiceList - :rtype: twilio.rest.authy.v1.service.ServiceList - """ - super(ServiceList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) - - def create(self, friendly_name, push=values.unset, - twilio_authy_sandbox_mode=values.unset): - """ - Create the ServiceInstance - - :param unicode friendly_name: A human readable description of this resource. - :param unicode push: Optional service level push factors configuration - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The created ServiceInstance - :rtype: twilio.rest.authy.v1.service.ServiceInstance - """ - data = values.of({'FriendlyName': friendly_name, 'Push': push, }) - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_sandbox_mode, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) - - return ServiceInstance(self._version, payload, ) - - def stream(self, twilio_authy_sandbox_mode=values.unset, 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 unicode twilio_authy_sandbox_mode: The Twilio-Authy-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.authy.v1.service.ServiceInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, twilio_authy_sandbox_mode=values.unset, 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 unicode twilio_authy_sandbox_mode: The Twilio-Authy-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.authy.v1.service.ServiceInstance] - """ - return list(self.stream( - twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, - limit=limit, - page_size=page_size, - )) - - def page(self, twilio_authy_sandbox_mode=values.unset, 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 unicode twilio_authy_sandbox_mode: The Twilio-Authy-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 ServiceInstance - :rtype: twilio.rest.authy.v1.service.ServicePage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_sandbox_mode, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, headers=headers, ) - - 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.authy.v1.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: A string that uniquely identifies this Service. - - :returns: twilio.rest.authy.v1.service.ServiceContext - :rtype: twilio.rest.authy.v1.service.ServiceContext - """ - return ServiceContext(self._version, sid=sid, ) - - def __call__(self, sid): - """ - Constructs a ServiceContext - - :param sid: A string that uniquely identifies this Service. - - :returns: twilio.rest.authy.v1.service.ServiceContext - :rtype: twilio.rest.authy.v1.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.authy.v1.service.ServicePage - :rtype: twilio.rest.authy.v1.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.authy.v1.service.ServiceInstance - :rtype: twilio.rest.authy.v1.service.ServiceInstance - """ - return ServiceInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ServiceContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, sid): - """ - Initialize the ServiceContext - - :param Version version: Version that contains the resource - :param sid: A string that uniquely identifies this Service. - - :returns: twilio.rest.authy.v1.service.ServiceContext - :rtype: twilio.rest.authy.v1.service.ServiceContext - """ - super(ServiceContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) - - # Dependents - self._entities = None - - def delete(self, twilio_authy_sandbox_mode=values.unset): - """ - Deletes the ServiceInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_sandbox_mode, }) - - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) - - def fetch(self, twilio_authy_sandbox_mode=values.unset): - """ - Fetch the ServiceInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The fetched ServiceInstance - :rtype: twilio.rest.authy.v1.service.ServiceInstance - """ - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_sandbox_mode, }) - - payload = self._version.fetch(method='GET', uri=self._uri, headers=headers, ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - - def update(self, friendly_name=values.unset, push=values.unset, - twilio_authy_sandbox_mode=values.unset): - """ - Update the ServiceInstance - - :param unicode friendly_name: A human readable description of this resource. - :param unicode push: Optional service level push factors configuration - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The updated ServiceInstance - :rtype: twilio.rest.authy.v1.service.ServiceInstance - """ - data = values.of({'FriendlyName': friendly_name, 'Push': push, }) - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_sandbox_mode, }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - - @property - def entities(self): - """ - Access the entities - - :returns: twilio.rest.authy.v1.service.entity.EntityList - :rtype: twilio.rest.authy.v1.service.entity.EntityList - """ - if self._entities is None: - self._entities = EntityList(self._version, service_sid=self._solution['sid'], ) - return self._entities - - def __repr__(self): - """ - Provide 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.authy.v1.service.ServiceInstance - :rtype: twilio.rest.authy.v1.service.ServiceInstance - """ - super(ServiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'friendly_name': payload.get('friendly_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'), - 'configuration': payload.get('configuration'), - } - - # 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.authy.v1.service.ServiceContext - """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Service. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def friendly_name(self): - """ - :returns: A human readable description of this resource. - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date this Service was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Service was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: Nested resource URLs. - :rtype: unicode - """ - return self._properties['links'] - - @property - def configuration(self): - """ - :returns: The service level configuration of all the factor types. - :rtype: dict - """ - return self._properties['configuration'] - - def delete(self, twilio_authy_sandbox_mode=values.unset): - """ - Deletes the ServiceInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete(twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, ) - - def fetch(self, twilio_authy_sandbox_mode=values.unset): - """ - Fetch the ServiceInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The fetched ServiceInstance - :rtype: twilio.rest.authy.v1.service.ServiceInstance - """ - return self._proxy.fetch(twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, ) - - def update(self, friendly_name=values.unset, push=values.unset, - twilio_authy_sandbox_mode=values.unset): - """ - Update the ServiceInstance - - :param unicode friendly_name: A human readable description of this resource. - :param unicode push: Optional service level push factors configuration - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The updated ServiceInstance - :rtype: twilio.rest.authy.v1.service.ServiceInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - push=push, - twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, - ) - - @property - def entities(self): - """ - Access the entities - - :returns: twilio.rest.authy.v1.service.entity.EntityList - :rtype: twilio.rest.authy.v1.service.entity.EntityList - """ - return self._proxy.entities - - def __repr__(self): - """ - Provide 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/authy/v1/service/entity/__init__.py b/twilio/rest/authy/v1/service/entity/__init__.py deleted file mode 100644 index 7d49868f76..0000000000 --- a/twilio/rest/authy/v1/service/entity/__init__.py +++ /dev/null @@ -1,453 +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.authy.v1.service.entity.factor import FactorList - - -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 - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - - :returns: twilio.rest.authy.v1.service.entity.EntityList - :rtype: twilio.rest.authy.v1.service.entity.EntityList - """ - super(EntityList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Entities'.format(**self._solution) - - def create(self, identity, twilio_authy_sandbox_mode=values.unset): - """ - Create the EntityInstance - - :param unicode identity: Unique identity of the Entity - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The created EntityInstance - :rtype: twilio.rest.authy.v1.service.entity.EntityInstance - """ - data = values.of({'Identity': identity, }) - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_sandbox_mode, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) - - return EntityInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def stream(self, twilio_authy_sandbox_mode=values.unset, limit=None, - page_size=None): - """ - 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 unicode twilio_authy_sandbox_mode: The Twilio-Authy-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.authy.v1.service.entity.EntityInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, twilio_authy_sandbox_mode=values.unset, limit=None, - page_size=None): - """ - 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 unicode twilio_authy_sandbox_mode: The Twilio-Authy-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.authy.v1.service.entity.EntityInstance] - """ - return list(self.stream( - twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, - limit=limit, - page_size=page_size, - )) - - def page(self, twilio_authy_sandbox_mode=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of EntityInstance records from the API. - Request is executed immediately - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-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.authy.v1.service.entity.EntityPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_sandbox_mode, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, headers=headers, ) - - return EntityPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - 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.authy.v1.service.entity.EntityPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return EntityPage(self._version, response, self._solution) - - def get(self, identity): - """ - Constructs a EntityContext - - :param identity: Unique identity of the Entity - - :returns: twilio.rest.authy.v1.service.entity.EntityContext - :rtype: twilio.rest.authy.v1.service.entity.EntityContext - """ - return EntityContext(self._version, service_sid=self._solution['service_sid'], identity=identity, ) - - def __call__(self, identity): - """ - Constructs a EntityContext - - :param identity: Unique identity of the Entity - - :returns: twilio.rest.authy.v1.service.entity.EntityContext - :rtype: twilio.rest.authy.v1.service.entity.EntityContext - """ - return EntityContext(self._version, service_sid=self._solution['service_sid'], identity=identity, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class 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. """ - - def __init__(self, version, response, solution): - """ - Initialize the EntityPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - - :returns: twilio.rest.authy.v1.service.entity.EntityPage - :rtype: twilio.rest.authy.v1.service.entity.EntityPage - """ - super(EntityPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of EntityInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.authy.v1.service.entity.EntityInstance - :rtype: twilio.rest.authy.v1.service.entity.EntityInstance - """ - return EntityInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -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. """ - - def __init__(self, version, service_sid, identity): - """ - Initialize the EntityContext - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param identity: Unique identity of the Entity - - :returns: twilio.rest.authy.v1.service.entity.EntityContext - :rtype: twilio.rest.authy.v1.service.entity.EntityContext - """ - 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) - - # Dependents - self._factors = None - - def delete(self, twilio_authy_sandbox_mode=values.unset): - """ - Deletes the EntityInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_sandbox_mode, }) - - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) - - def fetch(self, twilio_authy_sandbox_mode=values.unset): - """ - Fetch the EntityInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The fetched EntityInstance - :rtype: twilio.rest.authy.v1.service.entity.EntityInstance - """ - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_sandbox_mode, }) - - payload = self._version.fetch(method='GET', uri=self._uri, headers=headers, ) - - return EntityInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - ) - - @property - def factors(self): - """ - Access the factors - - :returns: twilio.rest.authy.v1.service.entity.factor.FactorList - :rtype: twilio.rest.authy.v1.service.entity.factor.FactorList - """ - if self._factors is None: - self._factors = FactorList( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - ) - return self._factors - - def __repr__(self): - """ - Provide 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 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. """ - - def __init__(self, version, payload, service_sid, identity=None): - """ - Initialize the EntityInstance - - :returns: twilio.rest.authy.v1.service.entity.EntityInstance - :rtype: twilio.rest.authy.v1.service.entity.EntityInstance - """ - super(EntityInstance, self).__init__(version) - - # 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'), - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'identity': identity or self._properties['identity'], } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: EntityContext for this EntityInstance - :rtype: twilio.rest.authy.v1.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 - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Entity. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def identity(self): - """ - :returns: Unique identity of the Entity - :rtype: unicode - """ - return self._properties['identity'] - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: Service Sid. - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def date_created(self): - """ - :returns: The date this Entity was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Entity was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: Nested resource URLs. - :rtype: unicode - """ - return self._properties['links'] - - def delete(self, twilio_authy_sandbox_mode=values.unset): - """ - Deletes the EntityInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete(twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, ) - - def fetch(self, twilio_authy_sandbox_mode=values.unset): - """ - Fetch the EntityInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The fetched EntityInstance - :rtype: twilio.rest.authy.v1.service.entity.EntityInstance - """ - return self._proxy.fetch(twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, ) - - @property - def factors(self): - """ - Access the factors - - :returns: twilio.rest.authy.v1.service.entity.factor.FactorList - :rtype: twilio.rest.authy.v1.service.entity.factor.FactorList - """ - return self._proxy.factors - - def __repr__(self): - """ - Provide 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/authy/v1/service/entity/factor/__init__.py b/twilio/rest/authy/v1/service/entity/factor/__init__.py deleted file mode 100644 index d523e216ad..0000000000 --- a/twilio/rest/authy/v1/service/entity/factor/__init__.py +++ /dev/null @@ -1,597 +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.authy.v1.service.entity.factor.challenge import ChallengeList - - -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 - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param identity: Unique identity of the Entity - - :returns: twilio.rest.authy.v1.service.entity.factor.FactorList - :rtype: twilio.rest.authy.v1.service.entity.factor.FactorList - """ - super(FactorList, self).__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, binding, friendly_name, factor_type, config, - twilio_authy_sandbox_mode=values.unset, authorization=values.unset): - """ - 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_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - :param unicode authorization: The Authorization HTTP request header - - :returns: The created FactorInstance - :rtype: twilio.rest.authy.v1.service.entity.factor.FactorInstance - """ - data = values.of({ - 'Binding': binding, - 'FriendlyName': friendly_name, - 'FactorType': factor_type, - 'Config': config, - }) - headers = values.of({ - 'Twilio-Authy-Sandbox-Mode': twilio_authy_sandbox_mode, - 'Authorization': authorization, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) - - return FactorInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - ) - - def stream(self, twilio_authy_sandbox_mode=values.unset, limit=None, - page_size=None): - """ - Streams FactorInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-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.authy.v1.service.entity.factor.FactorInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, twilio_authy_sandbox_mode=values.unset, limit=None, - page_size=None): - """ - 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 unicode twilio_authy_sandbox_mode: The Twilio-Authy-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.authy.v1.service.entity.factor.FactorInstance] - """ - return list(self.stream( - twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, - limit=limit, - page_size=page_size, - )) - - def page(self, twilio_authy_sandbox_mode=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of FactorInstance records from the API. - Request is executed immediately - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-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.authy.v1.service.entity.factor.FactorPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_sandbox_mode, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, headers=headers, ) - - return FactorPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of FactorInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of FactorInstance - :rtype: twilio.rest.authy.v1.service.entity.factor.FactorPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return FactorPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a FactorContext - - :param sid: A string that uniquely identifies this Factor. - - :returns: twilio.rest.authy.v1.service.entity.factor.FactorContext - :rtype: twilio.rest.authy.v1.service.entity.factor.FactorContext - """ - return FactorContext( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a FactorContext - - :param sid: A string that uniquely identifies this Factor. - - :returns: twilio.rest.authy.v1.service.entity.factor.FactorContext - :rtype: twilio.rest.authy.v1.service.entity.factor.FactorContext - """ - return FactorContext( - 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 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. """ - - def __init__(self, version, response, solution): - """ - Initialize the FactorPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - :param identity: Unique identity of the Entity - - :returns: twilio.rest.authy.v1.service.entity.factor.FactorPage - :rtype: twilio.rest.authy.v1.service.entity.factor.FactorPage - """ - super(FactorPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of FactorInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.authy.v1.service.entity.factor.FactorInstance - :rtype: twilio.rest.authy.v1.service.entity.factor.FactorInstance - """ - return FactorInstance( - 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 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. """ - - def __init__(self, version, service_sid, identity, sid): - """ - Initialize the FactorContext - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param identity: Unique identity of the Entity - :param sid: A string that uniquely identifies this Factor. - - :returns: twilio.rest.authy.v1.service.entity.factor.FactorContext - :rtype: twilio.rest.authy.v1.service.entity.factor.FactorContext - """ - super(FactorContext, self).__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) - - # Dependents - self._challenges = None - - def delete(self, twilio_authy_sandbox_mode=values.unset): - """ - Deletes the FactorInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_sandbox_mode, }) - - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) - - def fetch(self, twilio_authy_sandbox_mode=values.unset): - """ - Fetch the FactorInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The fetched FactorInstance - :rtype: twilio.rest.authy.v1.service.entity.factor.FactorInstance - """ - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_sandbox_mode, }) - - payload = self._version.fetch(method='GET', uri=self._uri, headers=headers, ) - - return FactorInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - sid=self._solution['sid'], - ) - - def update(self, auth_payload=values.unset, friendly_name=values.unset, - config=values.unset, twilio_authy_sandbox_mode=values.unset): - """ - 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_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The updated FactorInstance - :rtype: twilio.rest.authy.v1.service.entity.factor.FactorInstance - """ - data = values.of({'AuthPayload': auth_payload, 'FriendlyName': friendly_name, 'Config': config, }) - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_sandbox_mode, }) - - 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'], - ) - - @property - def challenges(self): - """ - Access the challenges - - :returns: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeList - :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeList - """ - if self._challenges is None: - self._challenges = ChallengeList( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - factor_sid=self._solution['sid'], - ) - return self._challenges - - def __repr__(self): - """ - Provide 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 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 FactorStatuses(object): - UNVERIFIED = "unverified" - VERIFIED = "verified" - - class FactorTypes(object): - APP_PUSH = "app-push" - SMS = "sms" - TOTP = "totp" - PUSH = "push" - - def __init__(self, version, payload, service_sid, identity, sid=None): - """ - Initialize the FactorInstance - - :returns: twilio.rest.authy.v1.service.entity.factor.FactorInstance - :rtype: twilio.rest.authy.v1.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'), - 'links': payload.get('links'), - } - - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'identity': identity, - 'sid': sid or self._properties['sid'], - } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FactorContext for this FactorInstance - :rtype: twilio.rest.authy.v1.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 - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Factor. - :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 identity of the Entity - :rtype: unicode - """ - return self._properties['identity'] - - @property - def date_created(self): - """ - :returns: The date this Factor was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Factor was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def friendly_name(self): - """ - :returns: A human readable description of this resource. - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def status(self): - """ - :returns: The Status of this Factor - :rtype: FactorInstance.FactorStatuses - """ - return self._properties['status'] - - @property - def factor_type(self): - """ - :returns: The Type of this Factor - :rtype: FactorInstance.FactorTypes - """ - return self._properties['factor_type'] - - @property - def config(self): - """ - :returns: The config - :rtype: dict - """ - return self._properties['config'] - - @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 delete(self, twilio_authy_sandbox_mode=values.unset): - """ - Deletes the FactorInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete(twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, ) - - def fetch(self, twilio_authy_sandbox_mode=values.unset): - """ - Fetch the FactorInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The fetched FactorInstance - :rtype: twilio.rest.authy.v1.service.entity.factor.FactorInstance - """ - return self._proxy.fetch(twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, ) - - def update(self, auth_payload=values.unset, friendly_name=values.unset, - config=values.unset, twilio_authy_sandbox_mode=values.unset): - """ - 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_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The updated FactorInstance - :rtype: twilio.rest.authy.v1.service.entity.factor.FactorInstance - """ - return self._proxy.update( - auth_payload=auth_payload, - friendly_name=friendly_name, - config=config, - twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, - ) - - @property - def challenges(self): - """ - Access the challenges - - :returns: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeList - :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeList - """ - return self._proxy.challenges - - def __repr__(self): - """ - Provide 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/authy/v1/service/entity/factor/challenge.py b/twilio/rest/authy/v1/service/entity/factor/challenge.py deleted file mode 100644 index 53aa594e4c..0000000000 --- a/twilio/rest/authy/v1/service/entity/factor/challenge.py +++ /dev/null @@ -1,620 +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, factor_sid): - """ - Initialize the ChallengeList - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param identity: Unique identity of the Entity - :param factor_sid: Factor Sid. - - :returns: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeList - :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeList - """ - super(ChallengeList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, 'identity': identity, 'factor_sid': factor_sid, } - self._uri = '/Services/{service_sid}/Entities/{identity}/Factors/{factor_sid}/Challenges'.format(**self._solution) - - def create(self, expiration_date=values.unset, details=values.unset, - hidden_details=values.unset, twilio_authy_sandbox_mode=values.unset): - """ - Create the ChallengeInstance - - :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_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The created ChallengeInstance - :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance - """ - data = values.of({ - 'ExpirationDate': serialize.iso8601_datetime(expiration_date), - 'Details': details, - 'HiddenDetails': hidden_details, - }) - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_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'], - factor_sid=self._solution['factor_sid'], - ) - - def stream(self, status=values.unset, twilio_authy_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 ChallengeInstance.ChallengeStatuses status: The Status of theChallenges to fetch - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-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.authy.v1.service.entity.factor.challenge.ChallengeInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page( - status=status, - twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, status=values.unset, twilio_authy_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 ChallengeInstance.ChallengeStatuses status: The Status of theChallenges to fetch - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-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.authy.v1.service.entity.factor.challenge.ChallengeInstance] - """ - return list(self.stream( - status=status, - twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, - limit=limit, - page_size=page_size, - )) - - def page(self, status=values.unset, twilio_authy_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 ChallengeInstance.ChallengeStatuses status: The Status of theChallenges to fetch - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-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.authy.v1.service.entity.factor.challenge.ChallengePage - """ - data = values.of({ - 'Status': status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_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.authy.v1.service.entity.factor.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, or `latest`. - - :returns: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeContext - :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeContext - """ - return ChallengeContext( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - factor_sid=self._solution['factor_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a ChallengeContext - - :param sid: A string that uniquely identifies this Challenge, or `latest`. - - :returns: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeContext - :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeContext - """ - return ChallengeContext( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - factor_sid=self._solution['factor_sid'], - 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 identity of the Entity - :param factor_sid: Factor Sid. - - :returns: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengePage - :rtype: twilio.rest.authy.v1.service.entity.factor.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.authy.v1.service.entity.factor.challenge.ChallengeInstance - :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance - """ - return ChallengeInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - factor_sid=self._solution['factor_sid'], - ) - - 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, factor_sid, sid): - """ - Initialize the ChallengeContext - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param identity: Unique identity of the Entity - :param factor_sid: Factor Sid. - :param sid: A string that uniquely identifies this Challenge, or `latest`. - - :returns: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeContext - :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeContext - """ - super(ChallengeContext, self).__init__(version) - - # Path Solution - self._solution = { - 'service_sid': service_sid, - 'identity': identity, - 'factor_sid': factor_sid, - 'sid': sid, - } - self._uri = '/Services/{service_sid}/Entities/{identity}/Factors/{factor_sid}/Challenges/{sid}'.format(**self._solution) - - def delete(self, twilio_authy_sandbox_mode=values.unset): - """ - Deletes the ChallengeInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_sandbox_mode, }) - - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) - - def fetch(self, twilio_authy_sandbox_mode=values.unset): - """ - Fetch the ChallengeInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The fetched ChallengeInstance - :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance - """ - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_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'], - factor_sid=self._solution['factor_sid'], - sid=self._solution['sid'], - ) - - def update(self, auth_payload=values.unset, - twilio_authy_sandbox_mode=values.unset): - """ - Update the ChallengeInstance - - :param unicode auth_payload: Optional payload to verify the Challenge - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The updated ChallengeInstance - :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance - """ - data = values.of({'AuthPayload': auth_payload, }) - headers = values.of({'Twilio-Authy-Sandbox-Mode': twilio_authy_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'], - factor_sid=self._solution['factor_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 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): - APP_PUSH = "app-push" - SMS = "sms" - TOTP = "totp" - PUSH = "push" - - def __init__(self, version, payload, service_sid, identity, factor_sid, - sid=None): - """ - Initialize the ChallengeInstance - - :returns: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance - :rtype: twilio.rest.authy.v1.service.entity.factor.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, - 'factor_sid': factor_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: ChallengeContext for this ChallengeInstance - :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeContext - """ - if self._context is None: - self._context = ChallengeContext( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - factor_sid=self._solution['factor_sid'], - 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 identity 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 delete(self, twilio_authy_sandbox_mode=values.unset): - """ - Deletes the ChallengeInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete(twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, ) - - def fetch(self, twilio_authy_sandbox_mode=values.unset): - """ - Fetch the ChallengeInstance - - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The fetched ChallengeInstance - :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance - """ - return self._proxy.fetch(twilio_authy_sandbox_mode=twilio_authy_sandbox_mode, ) - - def update(self, auth_payload=values.unset, - twilio_authy_sandbox_mode=values.unset): - """ - Update the ChallengeInstance - - :param unicode auth_payload: Optional payload to verify the Challenge - :param unicode twilio_authy_sandbox_mode: The Twilio-Authy-Sandbox-Mode HTTP request header - - :returns: The updated ChallengeInstance - :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance - """ - return self._proxy.update( - auth_payload=auth_payload, - twilio_authy_sandbox_mode=twilio_authy_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/autopilot/__init__.py b/twilio/rest/autopilot/__init__.py deleted file mode 100644 index 6a7883e2a9..0000000000 --- a/twilio/rest/autopilot/__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.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 - - 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 5053e5117b..0000000000 --- a/twilio/rest/autopilot/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.autopilot.v1.assistant import AssistantList - - -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 - - @property - def assistants(self): - """ - :rtype: twilio.rest.autopilot.v1.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/autopilot/v1/assistant/__init__.py b/twilio/rest/autopilot/v1/assistant/__init__.py deleted file mode 100644 index 5c8648371c..0000000000 --- a/twilio/rest/autopilot/v1/assistant/__init__.py +++ /dev/null @@ -1,741 +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.export_assistant import ExportAssistantList -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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists AssistantInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.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 - self._export_assistant = 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 - - @property - def export_assistant(self): - """ - Access the export_assistant - - :returns: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantList - :rtype: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantList - """ - if self._export_assistant is None: - self._export_assistant = ExportAssistantList(self._version, assistant_sid=self._solution['sid'], ) - return self._export_assistant - - def __repr__(self): - """ - Provide 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 - - @property - def export_assistant(self): - """ - Access the export_assistant - - :returns: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantList - :rtype: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantList - """ - return self._proxy.export_assistant - - def __repr__(self): - """ - Provide 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/export_assistant.py b/twilio/rest/autopilot/v1/assistant/export_assistant.py deleted file mode 100644 index 48a7e8c345..0000000000 --- a/twilio/rest/autopilot/v1/assistant/export_assistant.py +++ /dev/null @@ -1,277 +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 ExportAssistantList(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 ExportAssistantList - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant to export. - - :returns: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantList - :rtype: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantList - """ - super(ExportAssistantList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - - def get(self): - """ - Constructs a ExportAssistantContext - - :returns: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantContext - :rtype: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantContext - """ - return ExportAssistantContext(self._version, assistant_sid=self._solution['assistant_sid'], ) - - def __call__(self): - """ - Constructs a ExportAssistantContext - - :returns: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantContext - :rtype: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantContext - """ - return ExportAssistantContext(self._version, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ExportAssistantPage(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 ExportAssistantPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The SID of the Assistant to export. - - :returns: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantPage - :rtype: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantPage - """ - super(ExportAssistantPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ExportAssistantInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantInstance - :rtype: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantInstance - """ - return ExportAssistantInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ExportAssistantContext(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 ExportAssistantContext - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant to export. - - :returns: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantContext - :rtype: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantContext - """ - super(ExportAssistantContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - self._uri = '/Assistants/{assistant_sid}/Export'.format(**self._solution) - - def fetch(self): - """ - Fetch the ExportAssistantInstance - - :returns: The fetched ExportAssistantInstance - :rtype: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return ExportAssistantInstance( - 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 ExportAssistantInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - class Status(object): - COMPLETED = "completed" - FAILED = "failed" - - def __init__(self, version, payload, assistant_sid): - """ - Initialize the ExportAssistantInstance - - :returns: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantInstance - :rtype: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantInstance - """ - super(ExportAssistantInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'status': payload.get('status'), - 'error_code': deserialize.integer(payload.get('error_code')), - 'url': payload.get('url'), - 'schema': payload.get('schema'), - } - - # 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: ExportAssistantContext for this ExportAssistantInstance - :rtype: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantContext - """ - if self._context is None: - self._context = ExportAssistantContext(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 to export. - :rtype: unicode - """ - return self._properties['assistant_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 status(self): - """ - :returns: The status of the export - :rtype: ExportAssistantInstance.Status - """ - return self._properties['status'] - - @property - def error_code(self): - """ - :returns: More information about why the export failed, if `status` is `failed` - :rtype: unicode - """ - return self._properties['error_code'] - - @property - def url(self): - """ - :returns: The absolute URL of the Export resource. - :rtype: unicode - """ - return self._properties['url'] - - @property - def schema(self): - """ - :returns: The JSON string that describes the requested Assistant. - :rtype: dict - """ - return self._properties['schema'] - - def fetch(self): - """ - Fetch the ExportAssistantInstance - - :returns: The fetched ExportAssistantInstance - :rtype: twilio.rest.autopilot.v1.assistant.export_assistant.ExportAssistantInstance - """ - 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 bbe6950f1b..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists FieldTypeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.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 0e7cb9975b..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'], limits['page_limit']) - - def list(self, language=values.unset, limit=None, page_size=None): - """ - Lists FieldValueInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode language: The 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 6b7596641b..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists ModelBuildInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.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 fcada5dd08..0000000000 --- a/twilio/rest/autopilot/v1/assistant/query.py +++ /dev/null @@ -1,519 +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, 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, language=values.unset, model_build=values.unset, - status=values.unset, limit=None, page_size=None): - """ - Lists QueryInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode language: The 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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, - limit=limit, - page_size=page_size, - )) - - def page(self, language=values.unset, model_build=values.unset, - status=values.unset, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of QueryInstance records from the API. - Request is executed immediately - - :param unicode language: The 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 str page_token: PageToken provided by the API - :param int page_number: 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, - '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 ef910d581c..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'], limits['page_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 f9726cd19d..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists FieldInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.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 719af44214..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'], limits['page_limit']) - - def list(self, language=values.unset, limit=None, page_size=None): - """ - Lists SampleInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode language: The 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 f3a954c2c4..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'], limits['page_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/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..2bb449d2a4 100644 --- a/twilio/rest/bulkexports/v1/export/__init__.py +++ b/twilio/rest/bulkexports/v1/export/__init__.py @@ -1,295 +1,318 @@ -# 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.api_response import ApiResponse 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 + 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: ExportContext for this ExportInstance + """ + if self._context is None: + self._context = ExportContext( + self._version, + resource_type=self._solution["resource_type"], + ) + return self._context - :returns: twilio.rest.bulkexports.v1.export.ExportList - :rtype: twilio.rest.bulkexports.v1.export.ExportList + def fetch(self) -> "ExportInstance": """ - super(ExportList, self).__init__(version) + Fetch the ExportInstance - # Path Solution - self._solution = {} - # Components - self._jobs = None + :returns: The fetched ExportInstance + """ + return self._proxy.fetch() - @property - def jobs(self): + async def fetch_async(self) -> "ExportInstance": """ - Access the jobs + Asynchronous coroutine to 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 await self._proxy.fetch_async() - def get(self, resource_type): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a ExportContext + Fetch the ExportInstance with HTTP info - :param resource_type: The type of communication – Messages, Calls - :returns: twilio.rest.bulkexports.v1.export.ExportContext - :rtype: twilio.rest.bulkexports.v1.export.ExportContext + :returns: ApiResponse with instance, status code, and headers """ - return ExportContext(self._version, resource_type=resource_type, ) + return self._proxy.fetch_with_http_info() - def __call__(self, resource_type): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Constructs a ExportContext + Asynchronous coroutine to fetch the ExportInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() - :param resource_type: The type of communication – Messages, Calls + @property + def days(self) -> DayList: + """ + 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) - def get_instance(self, payload): - """ - Build an instance of ExportInstance + self._days: Optional[DayList] = None + self._export_custom_jobs: Optional[ExportCustomJobList] = None - :param dict payload: Payload response from the API + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.bulkexports.v1.export.ExportInstance - :rtype: twilio.rest.bulkexports.v1.export.ExportInstance + Returns: + tuple: (payload, status_code, headers) """ - return ExportInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ExportInstance: """ - Provide a friendly representation + Fetch the ExportInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched ExportInstance """ - return '' + payload, _, _ = self._fetch() + return ExportInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExportInstance and return response metadata -class ExportContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, resource_type): + :returns: ApiResponse with instance, status code, and headers """ - Initialize the ExportContext + payload, status_code, headers = self._fetch() + instance = ExportInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param Version version: Version that contains the resource - :param resource_type: The type of communication – Messages, Calls + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: twilio.rest.bulkexports.v1.export.ExportContext - :rtype: twilio.rest.bulkexports.v1.export.ExportContext + Returns: + tuple: (payload, status_code, headers) """ - super(ExportContext, self).__init__(version) - # Path Solution - self._solution = {'resource_type': resource_type, } - self._uri = '/Exports/{resource_type}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._days = None - self._export_custom_jobs = None + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + async def fetch_async(self) -> ExportInstance: """ - Fetch the ExportInstance + Asynchronous coroutine to fetch the ExportInstance + :returns: The fetched ExportInstance - :rtype: twilio.rest.bulkexports.v1.export.ExportInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = await self._fetch_async() + return ExportInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExportInstance and return response metadata - return ExportInstance(self._version, payload, resource_type=self._solution['resource_type'], ) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ExportInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 3b3b831c2a..b19395fde5 100644 --- a/twilio/rest/bulkexports/v1/export/day.py +++ b/twilio/rest/bulkexports/v1/export/day.py @@ -1,368 +1,674 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 + 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 resource_type: The type of communication – Messages, Calls + :returns: DayContext for this DayInstance + """ + if self._context is None: + self._context = DayContext( + self._version, + resource_type=self._solution["resource_type"], + day=self._solution["day"], + ) + return self._context - :returns: twilio.rest.bulkexports.v1.export.day.DayList - :rtype: twilio.rest.bulkexports.v1.export.day.DayList + def fetch(self) -> "DayInstance": """ - super(DayList, self).__init__(version) + Fetch the DayInstance - # 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): + :returns: The fetched 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. + return self._proxy.fetch() + + async def fetch_async(self) -> "DayInstance": + """ + Asynchronous coroutine to 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 await self._proxy.fetch_async() - page = self.page( - next_token=next_token, - previous_token=previous_token, - page_size=limits['page_size'], - ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DayInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, next_token=values.unset, previous_token=values.unset, limit=None, - page_size=None): + :returns: ApiResponse with instance, status code, and headers """ - Lists DayInstance 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_with_http_info() - :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) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DayInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.bulkexports.v1.export.day.DayInstance] + + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream( - next_token=next_token, - previous_token=previous_token, - limit=limit, - page_size=page_size, - )) + return await self._proxy.fetch_with_http_info_async() - def page(self, next_token=values.unset, previous_token=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of DayInstance records from the API. - Request is executed immediately + Provide a friendly representation - :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: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :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) + + # Path Solution + self._solution = { + "resource_type": resource_type, + "day": day, + } + self._uri = "/Exports/{resource_type}/Days/{day}".format(**self._solution) - return DayPage(self._version, response, self._solution) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - def get_page(self, target_url): + Returns: + tuple: (payload, status_code, headers) """ - 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 + headers = values.of({}) - :returns: Page of DayInstance - :rtype: twilio.rest.bulkexports.v1.export.day.DayPage + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DayInstance: + """ + Fetch the DayInstance + + + :returns: The fetched DayInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + payload, _, _ = self._fetch() + return DayInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + day=self._solution["day"], ) - return DayPage(self._version, response, self._solution) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DayInstance and return response metadata + - def get(self, day): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a DayContext + payload, status_code, headers = self._fetch() + instance = DayInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + day=self._solution["day"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param day: The date of the data in the file + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: twilio.rest.bulkexports.v1.export.day.DayContext - :rtype: twilio.rest.bulkexports.v1.export.day.DayContext + Returns: + tuple: (payload, status_code, headers) """ - return DayContext(self._version, resource_type=self._solution['resource_type'], day=day, ) - def __call__(self, day): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + 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, ) + payload, _, _ = await self._fetch_async() + return DayInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + day=self._solution["day"], + ) - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DayInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DayInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + day=self._solution["day"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 DayPage(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 get_instance(self, payload: Dict[str, Any]) -> DayInstance: """ - Initialize the DayPage + Build an instance of DayInstance - :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 payload: Payload response from the API + """ - :returns: twilio.rest.bulkexports.v1.export.day.DayPage - :rtype: twilio.rest.bulkexports.v1.export.day.DayPage + return DayInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + def __repr__(self) -> str: """ - super(DayPage, self).__init__(version, response) + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DayList(ListResource): + + def __init__(self, version: Version, resource_type: str): + """ + Initialize the DayList + + :param version: Version that contains the resource + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + + """ + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "resource_type": resource_type, + } + self._uri = "/Exports/{resource_type}/Days".format(**self._solution) - def get_instance(self, payload): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DayInstance]: """ - Build an instance of DayInstance + Streams DayInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - :param dict payload: Payload response from the API + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) - :returns: twilio.rest.bulkexports.v1.export.day.DayInstance - :rtype: twilio.rest.bulkexports.v1.export.day.DayInstance + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DayInstance]: """ - return DayInstance(self._version, payload, resource_type=self._solution['resource_type'], ) + Asynchronously streams DayInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - 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 + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return '' + Streams DayInstance and returns headers from first page -class DayContext(InstanceContext): - """ 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, resource_type, day): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Initialize the DayContext + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - :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 + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: twilio.rest.bulkexports.v1.export.day.DayContext - :rtype: twilio.rest.bulkexports.v1.export.day.DayContext + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(DayContext, self).__init__(version) + Asynchronously streams DayInstance and returns headers from first page - # Path Solution - self._solution = {'resource_type': resource_type, 'day': day, } - self._uri = '/Exports/{resource_type}/Days/{day}'.format(**self._solution) - 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: tuple of (generator, status_code, headers) where generator yields instances """ - Fetch the DayInstance + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :returns: The fetched DayInstance - :rtype: twilio.rest.bulkexports.v1.export.day.DayInstance + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DayInstance]: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Lists DayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - 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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + 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[DayInstance]: """ - Provide a friendly representation + 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: Machine friendly representation - :rtype: str + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DayInstance and returns headers from first page -class DayInstance(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, day=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: ApiResponse with list of instances, status code, and headers """ - Initialize the DayInstance + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: twilio.rest.bulkexports.v1.export.day.DayInstance - :rtype: twilio.rest.bulkexports.v1.export.day.DayInstance + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - super(DayInstance, self).__init__(version) + Asynchronously lists DayInstance and returns headers from first page - # 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'], } + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 _proxy(self): + :returns: ApiResponse with list of instances, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: DayContext for this DayInstance - :rtype: twilio.rest.bulkexports.v1.export.day.DayContext + 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: """ - if self._context is None: - self._context = DayContext( - self._version, - resource_type=self._solution['resource_type'], - day=self._solution['day'], - ) - return self._context + Retrieve a single page of DayInstance records from the API. + Request is executed immediately - @property - def redirect_to(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 DayInstance """ - :returns: The redirect_to - :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 DayPage(self._version, response, solution=self._solution) + + async def 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: """ - return self._properties['redirect_to'] + Asynchronously retrieve a single page of DayInstance records from the API. + Request is executed immediately - @property - def day(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 DayInstance """ - :returns: The date of the data in the file - :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 DayPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['day'] + Retrieve a single page with response metadata - @property - def size(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: ApiResponse with DayPage, status code, and headers """ - :returns: Size of the file in bytes - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DayPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['size'] + Asynchronously retrieve a single page with response metadata - @property - def create_date(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: ApiResponse with DayPage, status code, and headers """ - :returns: The date when resource is created - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DayPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> DayPage: """ - return self._properties['create_date'] + Retrieve a specific page of DayInstance records from the API. + Request is executed immediately - @property - def friendly_name(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of DayInstance """ - :returns: The friendly name specified when creating the job - :rtype: unicode + response = self._version.domain.twilio.request("GET", target_url) + return DayPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> DayPage: """ - return self._properties['friendly_name'] + Asynchronously retrieve a specific page of DayInstance records from the API. + Request is executed immediately - @property - def resource_type(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of DayInstance """ - :returns: The type of communication – Messages, Calls - :rtype: unicode + response = await self._version.domain.twilio.request_async("GET", target_url) + return DayPage(self._version, response, solution=self._solution) + + def get(self, day: str) -> DayContext: """ - return self._properties['resource_type'] + Constructs a DayContext - def fetch(self): + :param day: The ISO 8601 format date of the resources in the file, for a UTC day """ - Fetch the DayInstance + return DayContext( + self._version, resource_type=self._solution["resource_type"], day=day + ) - :returns: The fetched DayInstance - :rtype: twilio.rest.bulkexports.v1.export.day.DayInstance + def __call__(self, day: str) -> DayContext: """ - return self._proxy.fetch() + Constructs a DayContext + + :param day: The ISO 8601 format date of the resources in the file, for a UTC day + """ + return DayContext( + self._version, resource_type=self._solution["resource_type"], day=day + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 d814000d70..dee11094c1 100644 --- a/twilio/rest/bulkexports/v1/export/export_custom_job.py +++ b/twilio/rest/bulkexports/v1/export/export_custom_job.py @@ -1,333 +1,688 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class ExportCustomJobInstance(InstanceResource): + """ + :ivar friendly_name: The friendly name specified when creating the job + :ivar resource_type: The type of communication – Messages, Calls, Conferences, and Participants + :ivar start_day: The start day for the custom export specified when creating the job + :ivar end_day: The end day for the export specified when creating the job + :ivar webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. + :ivar webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + :ivar email: The optional email to send the completion notification to + :ivar job_sid: The unique job_sid returned when the custom export was created + :ivar details: The details of a job which is an object that contains an array of status grouped by `status` state. Each `status` object has a `status` string, a count which is the number of days in that `status`, and list of days in that `status`. The day strings are in the format yyyy-MM-dd. As an example, a currently running job may have a status object for COMPLETED and a `status` object for SUBMITTED each with its own count and list of days. + :ivar job_queue_position: This is the job position from the 1st in line. Your queue position will never increase. As jobs ahead of yours in the queue are processed, the queue position number will decrease + :ivar estimated_completion_time: this is the time estimated until your job is complete. This is calculated each time you request the job list. The time is calculated based on the current rate of job completion (which may vary) and your job queue position + """ + + def __init__(self, version: Version, payload: Dict[str, Any], resource_type: str): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.resource_type: Optional[str] = payload.get("resource_type") + self.start_day: Optional[str] = payload.get("start_day") + self.end_day: Optional[str] = payload.get("end_day") + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.email: Optional[str] = payload.get("email") + self.job_sid: Optional[str] = payload.get("job_sid") + self.details: Optional[List[Dict[str, object]]] = payload.get("details") + self.job_queue_position: Optional[str] = payload.get("job_queue_position") + self.estimated_completion_time: Optional[str] = payload.get( + "estimated_completion_time" + ) + + self._solution = { + "resource_type": resource_type, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExportCustomJobPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ExportCustomJobInstance: + """ + Build an instance of ExportCustomJobInstance + + :param payload: Payload response from the API + """ + + return ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class ExportCustomJobList(ListResource): - """ 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 ExportCustomJobList - :param Version version: Version that contains the resource - :param resource_type: The type of communication – Messages, Calls + :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.export_custom_job.ExportCustomJobList - :rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobList """ - super(ExportCustomJobList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'resource_type': resource_type, } - self._uri = '/Exports/{resource_type}/Jobs'.format(**self._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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "StartDay": start_day, + "EndDay": end_day, + "FriendlyName": friendly_name, + "WebhookUrl": webhook_url, + "WebhookMethod": webhook_method, + "Email": email, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - def stream(self, next_token=values.unset, previous_token=values.unset, - limit=None, page_size=None): + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + start_day: str, + end_day: str, + friendly_name: str, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ExportCustomJobInstance: + """ + Create the ExportCustomJobInstance + + :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd + :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. + :param friendly_name: The friendly name specified when creating the job + :param webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. If you set neither webhook nor email, you will have to check your job's status manually. + :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. + + :returns: The created ExportCustomJobInstance + """ + payload, _, _ = self._create( + start_day=start_day, + end_day=end_day, + friendly_name=friendly_name, + webhook_url=webhook_url, + webhook_method=webhook_method, + email=email, + ) + return ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ExportCustomJobInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + start_day=start_day, + end_day=end_day, + friendly_name=friendly_name, + webhook_url=webhook_url, + webhook_method=webhook_method, + email=email, + ) + instance = ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "StartDay": start_day, + "EndDay": end_day, + "FriendlyName": friendly_name, + "WebhookUrl": webhook_url, + "WebhookMethod": webhook_method, + "Email": email, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + start_day: str, + end_day: str, + friendly_name: str, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ExportCustomJobInstance: + """ + Asynchronously create the ExportCustomJobInstance + + :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd + :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. + :param friendly_name: The friendly name specified when creating the job + :param webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. If you set neither webhook nor email, you will have to check your job's status manually. + :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. + + :returns: The created ExportCustomJobInstance + """ + payload, _, _ = await self._create_async( + start_day=start_day, + end_day=end_day, + friendly_name=friendly_name, + webhook_url=webhook_url, + webhook_method=webhook_method, + email=email, + ) + return ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ExportCustomJobInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + start_day=start_day, + end_day=end_day, + friendly_name=friendly_name, + webhook_url=webhook_url, + webhook_method=webhook_method, + email=email, + ) + instance = ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExportCustomJobInstance]: """ Streams ExportCustomJobInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param 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 limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit 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.export_custom_job.ExportCustomJobInstance] """ limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["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'], limits['page_limit']) + return self._version.stream(page, limits["limit"]) - def list(self, next_token=values.unset, previous_token=values.unset, limit=None, - page_size=None): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[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. + 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 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 limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit 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.export_custom_job.ExportCustomJobInstance] """ - return list(self.stream( - next_token=next_token, - previous_token=previous_token, - 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, next_token=values.unset, previous_token=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Retrieve a single page of ExportCustomJobInstance records from the API. - Request is executed immediately + Streams ExportCustomJobInstance and returns headers from first page - :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.bulkexports.v1.export.export_custom_job.ExportCustomJobPage - """ - data = values.of({ - 'NextToken': next_token, - 'PreviousToken': previous_token, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - return ExportCustomJobPage(self._version, response, self._solution) + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - def get_page(self, target_url): + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Retrieve a specific page of ExportCustomJobInstance records from the API. - Request is executed immediately + Asynchronously streams ExportCustomJobInstance and returns headers from first page - :param str target_url: API-generated URL for the requested results page - :returns: Page of ExportCustomJobInstance - :rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobPage + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] ) - return ExportCustomJobPage(self._version, response, self._solution) + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - 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): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExportCustomJobInstance]: """ - Create the 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 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 + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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 created ExportCustomJobInstance - :rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobInstance + :returns: list that will contain up to limit results """ - 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'], + 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 - """ - return '' + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + :returns: list that will contain up to limit results + """ -class ExportCustomJobPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - def __init__(self, version, response, solution): + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Initialize the ExportCustomJobPage + Lists ExportCustomJobInstance and returns headers from first page - :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.bulkexports.v1.export.export_custom_job.ExportCustomJobPage - :rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobPage - """ - super(ExportCustomJobPage, self).__init__(version, 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) - # Path Solution - self._solution = solution + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - def get_instance(self, payload): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Build an instance of ExportCustomJobInstance + Asynchronously lists ExportCustomJobInstance and returns headers from first page + - :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: ApiResponse with list of instances, status code, and headers """ - return ExportCustomJobInstance( - self._version, - payload, - resource_type=self._solution['resource_type'], + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - def __repr__(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, + ) -> ExportCustomJobPage: """ - Provide a friendly representation + Retrieve a single page of ExportCustomJobInstance records from the API. + Request is executed immediately - :returns: Machine friendly representation - :rtype: str + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExportCustomJobInstance """ - return '' + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class ExportCustomJobInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExportCustomJobPage(self._version, response, solution=self._solution) - def __init__(self, version, payload, resource_type): + async def 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: """ - Initialize the ExportCustomJobInstance + Asynchronously retrieve a single page of ExportCustomJobInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - :returns: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobInstance - :rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobInstance + :returns: Page of ExportCustomJobInstance """ - super(ExportCustomJobInstance, self).__init__(version) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - # 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExportCustomJobPage(self._version, response, solution=self._solution) - @property - def resource_type(self): - """ - :returns: The type of communication – Messages, Calls - :rtype: unicode + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['resource_type'] + Retrieve a single page with response metadata - @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'] + :param page_token: PageToken provided by the 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 webhook_url(self): - """ - :returns: The optional webhook url called on completion - :rtype: unicode + :returns: ApiResponse with ExportCustomJobPage, status code, and headers """ - return self._properties['webhook_url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def webhook_method(self): - """ - :returns: This is the method used to call the webhook - :rtype: unicode - """ - return self._properties['webhook_method'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def email(self): + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ExportCustomJobPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The optional email to send the completion notification to - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ExportCustomJobPage, status code, and headers """ - return self._properties['email'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ExportCustomJobPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @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, solution=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, solution=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..2f8a7ef8f9 100644 --- a/twilio/rest/bulkexports/v1/export/job.py +++ b/twilio/rest/bulkexports/v1/export/job.py @@ -1,307 +1,381 @@ -# 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 from twilio.base import values +from twilio.base.api_response import ApiResponse 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[List[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 + 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: JobContext for this JobInstance + """ + if self._context is None: + self._context = JobContext( + self._version, + job_sid=self._solution["job_sid"], + ) + return self._context - :returns: twilio.rest.bulkexports.v1.export.job.JobList - :rtype: twilio.rest.bulkexports.v1.export.job.JobList + def delete(self) -> bool: """ - super(JobList, self).__init__(version) + Deletes the JobInstance - # Path Solution - self._solution = {} - def get(self, job_sid): + :returns: True if delete succeeds, False otherwise """ - Constructs a JobContext + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the JobInstance - :param job_sid: The job_sid - :returns: twilio.rest.bulkexports.v1.export.job.JobContext - :rtype: twilio.rest.bulkexports.v1.export.job.JobContext + :returns: True if delete succeeds, False otherwise """ - return JobContext(self._version, job_sid=job_sid, ) + return await self._proxy.delete_async() - def __call__(self, job_sid): + def delete_with_http_info(self) -> ApiResponse: """ - Constructs a JobContext + Deletes the JobInstance with HTTP info - :param job_sid: The job_sid - :returns: twilio.rest.bulkexports.v1.export.job.JobContext - :rtype: twilio.rest.bulkexports.v1.export.job.JobContext + :returns: ApiResponse with success boolean, status code, and headers """ - return JobContext(self._version, job_sid=job_sid, ) + return self._proxy.delete_with_http_info() - def __repr__(self): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine that deletes the JobInstance with HTTP info - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "JobInstance": """ - return '' + Fetch the JobInstance -class JobPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: The fetched JobInstance + """ + return self._proxy.fetch() - def __init__(self, version, response, solution): + async def fetch_async(self) -> "JobInstance": """ - Initialize the JobPage + Asynchronous coroutine to 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) + return await self._proxy.fetch_async() - # Path Solution - self._solution = solution + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the JobInstance with HTTP info - def get_instance(self, payload): + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of JobInstance + Asynchronous coroutine to fetch the JobInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return JobInstance(self._version, payload, ) + return await self._proxy.fetch_with_http_info_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) -> tuple: """ - Fetch the JobInstance + Internal helper for delete operation - :returns: The fetched JobInstance - :rtype: twilio.rest.bulkexports.v1.export.job.JobInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - 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_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ Deletes the JobInstance + :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + success, _, _ = self._delete() + return success - def __repr__(self): + def delete_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Deletes the JobInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with success boolean, status code, and headers """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation -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'), - } + Returns: + tuple: (success_boolean, status_code, headers) + """ - # Context - self._context = None - self._solution = {'job_sid': job_sid or self._properties['job_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 + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: JobContext for this JobInstance - :rtype: twilio.rest.bulkexports.v1.export.job.JobContext + async def delete_async(self) -> bool: """ - if self._context is None: - self._context = JobContext(self._version, job_sid=self._solution['job_sid'], ) - return self._context + Asynchronous coroutine that deletes the JobInstance - @property - def resource_type(self): - """ - :returns: The type of communication – Messages, Calls - :rtype: unicode + + :returns: True if delete succeeds, False otherwise """ - return self._properties['resource_type'] + success, _, _ = await self._delete_async() + return success - @property - def friendly_name(self): + async def delete_with_http_info_async(self) -> ApiResponse: """ - :returns: The friendly name specified when creating the job - :rtype: unicode + Asynchronous coroutine that deletes the JobInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers """ - return self._properties['friendly_name'] + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - @property - def details(self): + def _fetch(self) -> tuple: """ - :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 + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['details'] - @property - def start_day(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> JobInstance: """ - :returns: The start time for the export specified when creating the job - :rtype: unicode + Fetch the JobInstance + + + :returns: The fetched JobInstance """ - return self._properties['start_day'] + payload, _, _ = self._fetch() + return JobInstance( + self._version, + payload, + job_sid=self._solution["job_sid"], + ) - @property - def end_day(self): + def fetch_with_http_info(self) -> ApiResponse: """ - :returns: The end time for the export specified when creating the job - :rtype: unicode + Fetch the JobInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['end_day'] + payload, status_code, headers = self._fetch() + instance = JobInstance( + self._version, + payload, + job_sid=self._solution["job_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def job_sid(self): + async def _fetch_async(self) -> tuple: """ - :returns: The job_sid returned when the export was created - :rtype: unicode + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['job_sid'] - @property - def webhook_url(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> JobInstance: """ - :returns: The optional webhook url called on completion - :rtype: unicode + Asynchronous coroutine to fetch the JobInstance + + + :returns: The fetched JobInstance """ - return self._properties['webhook_url'] + payload, _, _ = await self._fetch_async() + return JobInstance( + self._version, + payload, + job_sid=self._solution["job_sid"], + ) - @property - def webhook_method(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: This is the method used to call the webhook - :rtype: unicode + Asynchronous coroutine to fetch the JobInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['webhook_method'] + payload, status_code, headers = await self._fetch_async() + instance = JobInstance( + self._version, + payload, + job_sid=self._solution["job_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def email(self): + def __repr__(self) -> str: """ - :returns: The optional email to send the completion notification to - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['email'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @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..d5b684b092 100644 --- a/twilio/rest/bulkexports/v1/export_configuration.py +++ b/twilio/rest/bulkexports/v1/export_configuration.py @@ -1,287 +1,498 @@ -# 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.api_response import ApiResponse 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, + } - def __init__(self, version): + self._context: Optional[ExportConfigurationContext] = None + + @property + def _proxy(self) -> "ExportConfigurationContext": """ - Initialize the ExportConfigurationList + 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: ExportConfigurationContext for this ExportConfigurationInstance + """ + if self._context is None: + self._context = ExportConfigurationContext( + self._version, + resource_type=self._solution["resource_type"], + ) + return self._context - :returns: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationList - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationList + def fetch(self) -> "ExportConfigurationInstance": """ - super(ExportConfigurationList, self).__init__(version) + Fetch the ExportConfigurationInstance - # Path Solution - self._solution = {} - def get(self, resource_type): + :returns: The fetched ExportConfigurationInstance """ - Constructs a ExportConfigurationContext + return self._proxy.fetch() + + async def fetch_async(self) -> "ExportConfigurationInstance": + """ + Asynchronous coroutine to fetch the ExportConfigurationInstance - :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 + :returns: The fetched ExportConfigurationInstance """ - return ExportConfigurationContext(self._version, resource_type=resource_type, ) + return await self._proxy.fetch_async() - def __call__(self, resource_type): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a ExportConfigurationContext + Fetch the ExportConfigurationInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - return ExportConfigurationContext(self._version, resource_type=resource_type, ) + return self._proxy.fetch_with_http_info() - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the ExportConfigurationInstance with HTTP info - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - return '' + return await self._proxy.fetch_with_http_info_async() + def update( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> "ExportConfigurationInstance": + """ + Update the ExportConfigurationInstance -class ExportConfigurationPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :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 - def __init__(self, version, response, solution): + :returns: The updated ExportConfigurationInstance """ - Initialize the ExportConfigurationPage + return self._proxy.update( + enabled=enabled, + webhook_url=webhook_url, + webhook_method=webhook_method, + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API + async def update_async( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> "ExportConfigurationInstance": + """ + Asynchronous coroutine to update the ExportConfigurationInstance + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: The updated ExportConfigurationInstance + """ + return await self._proxy.update_async( + enabled=enabled, + webhook_url=webhook_url, + webhook_method=webhook_method, + ) - :returns: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationPage - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationPage + def update_with_http_info( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ApiResponse: """ - super(ExportConfigurationPage, self).__init__(version, response) + Update the ExportConfigurationInstance with HTTP info - # Path Solution - self._solution = solution + :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 - def get_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of ExportConfigurationInstance + return self._proxy.update_with_http_info( + enabled=enabled, + webhook_url=webhook_url, + webhook_method=webhook_method, + ) - :param dict payload: Payload response from the API + async def update_with_http_info_async( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ExportConfigurationInstance with HTTP info - :returns: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationInstance - :rtype: twilio.rest.bulkexports.v1.export_configuration.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: ApiResponse with instance, status code, and headers """ - return ExportConfigurationInstance(self._version, payload, ) + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + 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, ) - + payload, _, _ = self._fetch() 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Update the ExportConfigurationInstance + Fetch the ExportConfigurationInstance and return response metadata - :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExportConfigurationInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - 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" + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ExportConfigurationInstance: + """ + Asynchronous coroutine to fetch the ExportConfigurationInstance + + + :returns: The fetched ExportConfigurationInstance + """ + payload, _, _ = await self._fetch_async() return ExportConfigurationInstance( self._version, payload, - resource_type=self._solution['resource_type'], + resource_type=self._solution["resource_type"], ) - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the ExportConfigurationInstance and return response metadata - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ExportConfigurationInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) -class ExportConfigurationInstance(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): + def _update( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> tuple: """ - Initialize the ExportConfigurationInstance + Internal helper for update operation - :returns: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationInstance - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ - 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): + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ExportConfigurationInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Update the ExportConfigurationInstance - :returns: ExportConfigurationContext for this ExportConfigurationInstance - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationContext + :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 """ - if self._context is None: - self._context = ExportConfigurationContext( - self._version, - resource_type=self._solution['resource_type'], - ) - return self._context + payload, _, _ = self._update( + enabled=enabled, webhook_url=webhook_url, webhook_method=webhook_method + ) + return ExportConfigurationInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) - @property - def enabled(self): + def update_with_http_info( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ApiResponse: """ - :returns: Whether files are automatically generated - :rtype: bool + Update the ExportConfigurationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['enabled'] + payload, status_code, headers = self._update( + enabled=enabled, webhook_url=webhook_url, webhook_method=webhook_method + ) + instance = ExportConfigurationInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def webhook_url(self): + 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, + ) -> tuple: """ - :returns: URL targeted at export - :rtype: unicode + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['webhook_url'] - @property - def webhook_method(self): + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + "WebhookUrl": webhook_url, + "WebhookMethod": webhook_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - :returns: Whether to GET or POST to the webhook url - :rtype: unicode + Asynchronous coroutine to update the ExportConfigurationInstance + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: The updated ExportConfigurationInstance """ - return self._properties['webhook_method'] + payload, _, _ = await self._update_async( + enabled=enabled, webhook_url=webhook_url, webhook_method=webhook_method + ) + return ExportConfigurationInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) - @property - def resource_type(self): + async def update_with_http_info_async( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ApiResponse: """ - :returns: The type of communication – Messages, Calls - :rtype: unicode + Asynchronous coroutine to update the ExportConfigurationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['resource_type'] + payload, status_code, headers = await self._update_async( + enabled=enabled, webhook_url=webhook_url, webhook_method=webhook_method + ) + instance = ExportConfigurationInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def url(self): + def __repr__(self) -> str: """ - :returns: The URL of this resource. - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['url'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def fetch(self): + +class ExportConfigurationList(ListResource): + + def __init__(self, version: Version): """ - Fetch the ExportConfigurationInstance + Initialize the ExportConfigurationList + + :param version: Version that contains the resource - :returns: The fetched ExportConfigurationInstance - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationInstance """ - return self._proxy.fetch() + super().__init__(version) - def update(self, enabled=values.unset, webhook_url=values.unset, - webhook_method=values.unset): + def get(self, resource_type: str) -> ExportConfigurationContext: """ - Update the ExportConfigurationInstance + Constructs a ExportConfigurationContext - :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 + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + """ + return ExportConfigurationContext(self._version, resource_type=resource_type) - :returns: The updated ExportConfigurationInstance - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationInstance + def __call__(self, resource_type: str) -> ExportConfigurationContext: + """ + Constructs a ExportConfigurationContext + + :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 cfe7c7ea46..a5d48dc68b 100644 --- a/twilio/rest/chat/v1/credential.py +++ b/twilio/rest/chat/v1/credential.py @@ -1,431 +1,907 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the Credential resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Credential resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the Credential resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } - def __init__(self, version): + self._context: Optional[CredentialContext] = None + + @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 + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v1.credential.CredentialList - :rtype: twilio.rest.chat.v1.credential.CredentialList + def delete(self) -> bool: """ - super(CredentialList, self).__init__(version) + Deletes the CredentialInstance - # Path Solution - self._solution = {} - self._uri = '/Credentials'.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.chat.v1.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.credential.CredentialInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "CredentialInstance": """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + 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 self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance - return CredentialPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched CredentialInstance """ - Retrieve a specific page of CredentialInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info - :returns: Page of CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info - return CredentialPage(self._version, response, self._solution) - 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: ApiResponse with instance, status code, and headers """ - Create the CredentialInstance + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance - :param 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 + :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 created CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + :returns: The updated CredentialInstance """ - data = values.of({ - 'Type': type, - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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 - return CredentialInstance(self._version, payload, ) + :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(self, sid): + :returns: The updated CredentialInstance """ - Constructs a CredentialContext + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - :param sid: The unique string that identifies the resource + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + :returns: ApiResponse with instance, status code, and headers """ - return CredentialContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - def __call__(self, sid): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Constructs a CredentialContext + Asynchronous coroutine to update the CredentialInstance with HTTP info - :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 certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + :returns: ApiResponse with instance, status code, and headers """ - return CredentialContext(self._version, sid=sid, ) + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialPage(Page): - """ """ +class CredentialContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the CredentialPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the CredentialContext - :returns: twilio.rest.chat.v1.credential.CredentialPage - :rtype: twilio.rest.chat.v1.credential.CredentialPage + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. """ - super(CredentialPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of CredentialInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.credential.CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + def delete(self) -> bool: """ - return CredentialInstance(self._version, payload, ) + Deletes the CredentialInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the CredentialInstance and return response metadata -class CredentialContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the CredentialContext - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource + headers = values.of({}) - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(CredentialContext, self).__init__(version) + Asynchronous coroutine that deletes the CredentialInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: """ Fetch the CredentialInstance + :returns: The fetched CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance and return response metadata - 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): + :returns: ApiResponse with instance, status code, and headers """ - Update the CredentialInstance + payload, status_code, headers = self._fetch() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :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 + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: The updated CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ - 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, ) + headers = values.of({}) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CredentialInstance: """ - Deletes the CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched CredentialInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, _, _ = await self._fetch_async() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the CredentialInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + payload, status_code, headers = await self._fetch_async() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + Returns: + tuple: (payload, status_code, headers) + """ -class CredentialInstance(InstanceResource): - """ """ + 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({}) - class PushService(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - def __init__(self, version, payload, sid=None): + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - Initialize the CredentialInstance + Update the CredentialInstance - :returns: twilio.rest.chat.v1.credential.CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance """ - super(CredentialInstance, self).__init__(version) + payload, _, _ = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CredentialInstance and return response metadata - # 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'), - } + :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. - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - 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 - :rtype: twilio.rest.chat.v1.credential.CredentialContext + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - if self._context is None: - self._context = CredentialContext(self._version, sid=self._solution['sid'], ) - return self._context + Asynchronous coroutine to update the CredentialInstance - @property - def sid(self): + :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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['sid'] + Asynchronous coroutine to update the CredentialInstance and return response metadata - @property - def account_sid(self): + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Provide a friendly representation + + :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 friendly_name(self): + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Build an instance of CredentialInstance + + :param payload: Payload response from the API """ - return self._properties['friendly_name'] - @property - def type(self): + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: """ - :returns: The type of push-notification service the credential is for - :rtype: CredentialInstance.PushService + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['type'] + return "" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource - @property - def sandbox(self): """ - :returns: [APN only] Whether to send the credential to sandbox APNs - :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, + ) -> tuple: """ - return self._properties['sandbox'] + Internal helper for create operation - @property - def date_created(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['date_created'] + Create the CredentialInstance - @property - def date_updated(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 RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Create the CredentialInstance and return response metadata - @property - def url(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: ApiResponse with instance, status code, and headers """ - :returns: The absolute URL of the Credential resource - :rtype: unicode + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: """ - return self._properties['url'] + Internal async helper for create operation - def fetch(self): + Returns: + tuple: (payload, status_code, headers) """ - Fetch the CredentialInstance - :returns: The fetched CredentialInstance - :rtype: twilio.rest.chat.v1.credential.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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._proxy.fetch() + Asynchronously create the CredentialInstance - 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 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 """ - Update the CredentialInstance + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata - :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 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 updated CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.update( + payload, status_code, headers = await self._create_async( + type=type, friendly_name=friendly_name, certificate=certificate, private_key=private_key, @@ -433,22 +909,394 @@ def update(self, friendly_name=values.unset, certificate=values.unset, api_key=api_key, secret=secret, ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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. - def delete(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 """ - Deletes the CredentialInstance + limits = self._version.read_limits(limit, page_size) + page = self.page(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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: """ - return self._proxy.delete() + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 c5f5b846eb..2d4c6b097d 100644 --- a/twilio/rest/chat/v1/service/__init__.py +++ b/twilio/rest/chat/v1/service/__init__.py @@ -1,913 +1,2640 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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, + } - def __init__(self, version): + self._context: Optional[ServiceContext] = None + + @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.chat.v1.service.ServiceList - :rtype: twilio.rest.chat.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 create(self, friendly_name): + :returns: True if delete succeeds, False otherwise """ - Create the ServiceInstance + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that 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, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info - return ServiceInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.ServiceInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + + :returns: The updated ServiceInstance + """ + payload, _, _ = self._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 ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) + return self._channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + if self._roles is None: + self._roles = RoleList( + self._version, + self._solution["sid"], + ) + return self._roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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 """ - 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) + return ServiceInstance(self._version, payload) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.ServiceInstance] + 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 ServiceInstance records from the API. - Request is executed immediately + return "" - :param str page_token: PageToken provided by the API - :param int page_number: 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) +class ServiceList(ListResource): - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def __init__(self, version: Version): + """ + Initialize the ServiceList - return ServicePage(self._version, response, self._solution) + :param version: Version that contains the resource - def get_page(self, target_url): """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately + super().__init__(version) - :param str target_url: API-generated URL for the requested results page + self._uri = "/Services" - :returns: Page of ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServicePage + def _create(self, friendly_name: str) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + + data = values.of( + { + "FriendlyName": friendly_name, + } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - return ServicePage(self._version, response, self._solution) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def get(self, sid): + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, friendly_name: str) -> ServiceInstance: """ - Constructs a ServiceContext + Create the ServiceInstance - :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.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + :returns: The created ServiceInstance """ - return ServiceContext(self._version, sid=sid, ) + payload, _, _ = self._create(friendly_name=friendly_name) + return ServiceInstance(self._version, payload) - def __call__(self, sid): + def create_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Constructs a ServiceContext + Create the ServiceInstance and return response metadata - :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.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + :returns: ApiResponse with instance, status code, and headers """ - return ServiceContext(self._version, sid=sid, ) + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _create_async(self, friendly_name: str) -> tuple: """ - Provide a friendly representation + Internal async helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class ServicePage(Page): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, response, solution): - """ - Initialize the ServicePage + headers["Accept"] = "application/json" - :param Version version: Version that contains the resource - :param Response response: Response from the API + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.chat.v1.service.ServicePage - :rtype: twilio.rest.chat.v1.service.ServicePage + async def create_async(self, friendly_name: str) -> ServiceInstance: """ - super(ServicePage, self).__init__(version, response) + Asynchronously create the ServiceInstance - # Path Solution - self._solution = solution + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - def get_instance(self, payload): + :returns: The created ServiceInstance """ - Build an instance of ServiceInstance + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return ServiceInstance(self._version, payload) - :param dict payload: Payload response from the API - - :returns: twilio.rest.chat.v1.service.ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: """ - return ServiceInstance(self._version, payload, ) + Asynchronously create the ServiceInstance and return response metadata - def __repr__(self): - """ - Provide a friendly representation + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: Machine friendly representation - :rtype: str + :returns: ApiResponse with instance, status code, and headers """ - return '' + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + 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. -class ServiceContext(InstanceContext): - """ """ + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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, sid): + :returns: Generator that will yield up to limit results """ - Initialize the ServiceContext + 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 sid: The unique string that identifies the resource + return self._version.stream(page, limits["limit"]) - :returns: twilio.rest.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: """ - super(ServiceContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) + 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. - # Dependents - self._channels = None - self._roles = None - self._users = None + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def fetch(self): + :returns: Generator that will yield up to limit results """ - Fetch the ServiceInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :returns: The fetched ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Streams ServiceInstance and returns headers from first page - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - def delete(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: tuple of (generator, status_code, headers) where generator yields instances """ - Deletes the ServiceInstance + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - :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): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Update the ServiceInstance + Asynchronously streams ServiceInstance and returns headers from first page - :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 - :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'], ) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 channels(self): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Access the channels + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :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'], ) - return self._channels + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - @property - def roles(self): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: """ - Access the roles + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: 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'], ) - return self._roles + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 users(self): + :returns: list that will contain up to limit results """ - 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'], ) - return self._users + 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[ServiceInstance]: """ - Provide a friendly representation + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: Machine friendly representation - :rtype: str + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] -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'), - } + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page - # 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 + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceContext + :returns: ApiResponse with list of instances, status code, and headers """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Asynchronously lists ServiceInstance and returns headers from first page - @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'] + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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_created(self): + :returns: ApiResponse with list of instances, status code, and headers """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + 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: """ - return self._properties['date_updated'] + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - @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 page_token: PageToken provided by the 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 default_channel_role_sid(self): - """ - :returns: The channel role assigned to users when they are added to a channel - :rtype: unicode + :returns: Page of ServiceInstance """ - return self._properties['default_channel_role_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @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'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def read_status_enabled(self): - """ - :returns: Whether the Message Consumption Horizon feature is enabled - :rtype: bool - """ - return self._properties['read_status_enabled'] + headers["Accept"] = "application/json" - @property - def reachability_enabled(self): - """ - :returns: Whether the Reachability Indicator feature is enabled for this Service instance - :rtype: bool - """ - return self._properties['reachability_enabled'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) - @property - def typing_indicator_timeout(self): + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: """ - :returns: How long in seconds to wait before assuming the user is no longer typing - :rtype: unicode - """ - return self._properties['typing_indicator_timeout'] + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - @property - def consumption_report_interval(self): - """ - :returns: DEPRECATED - :rtype: unicode - """ - return self._properties['consumption_report_interval'] + :param page_token: PageToken provided by the 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 limits(self): - """ - :returns: An object that describes the limits of the service instance - :rtype: dict + :returns: Page of ServiceInstance """ - return self._properties['limits'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def webhooks(self): - """ - :returns: An object that contains information about the webhooks configured for this service - :rtype: dict - """ - return self._properties['webhooks'] + headers = values.of({"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'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) - @property - def webhook_method(self): + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The HTTP method to use for both PRE and POST webhooks - :rtype: unicode - """ - return self._properties['webhook_method'] + Retrieve a single page with response metadata - @property - def webhook_filters(self): - """ - :returns: The list of WebHook events that are enabled for this Service instance - :rtype: unicode - """ - return self._properties['webhook_filters'] - @property - def notifications(self): - """ - :returns: The notification configuration for the Service instance - :rtype: dict - """ - return self._properties['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 - @property - def url(self): + :returns: ApiResponse with ServicePage, status code, and headers """ - :returns: The absolute URL of the Service resource - :rtype: unicode - """ - return self._properties['url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def links(self): - """ - :returns: The absolute URLs of the Service's Channels, Roles, and Users - :rtype: unicode - """ - return self._properties['links'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def fetch(self): - """ - Fetch the ServiceInstance + headers["Accept"] = "application/json" - :returns: The fetched ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance - """ - return self._proxy.fetch() + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - def delete(self): + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the ServiceInstance + Asynchronously retrieve a single page with response metadata - :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: ApiResponse with ServicePage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - 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): + 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 + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.chat.v1.service.channel.ChannelList - :rtype: twilio.rest.chat.v1.service.channel.ChannelList + :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 a16015e17d..d65a59603b 100644 --- a/twilio/rest/chat/v1/service/channel/__init__.py +++ b/twilio/rest/chat/v1/service/channel/__init__.py @@ -1,598 +1,1329 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page from twilio.rest.chat.v1.service.channel.invite import InviteList from twilio.rest.chat.v1.service.channel.member import MemberList from twilio.rest.chat.v1.service.channel.message import MessageList -class ChannelList(ListResource): - """ """ +class ChannelInstance(InstanceResource): + + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" + + """ + :ivar sid: The unique string that we created to identify the Channel resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Channel resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :ivar attributes: The JSON string that stores application-specific data. **Note** If this property has been assigned a value, it's only displayed in a FETCH action that returns a single resource; otherwise, it's null. If the attributes have not been set, `{}` is returned. + :ivar type: + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar created_by: The `identity` of the User that created the channel. If the Channel was created by using the API, the value is `system`. + :ivar members_count: The number of Members in the Channel. + :ivar messages_count: The number of Messages in the Channel. + :ivar url: The absolute URL of the Channel resource. + :ivar links: The absolute URLs of the [Members](https://www.twilio.com/docs/chat/api/members), [Messages](https://www.twilio.com/docs/chat/api/messages) , [Invites](https://www.twilio.com/docs/chat/api/invites) and, if it exists, the last [Message](https://www.twilio.com/docs/chat/api/messages) for the Channel. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.type: Optional["ChannelInstance.ChannelType"] = payload.get("type") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.members_count: Optional[int] = deserialize.integer( + payload.get("members_count") + ) + self.messages_count: Optional[int] = deserialize.integer( + payload.get("messages_count") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } - def __init__(self, version, service_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 - :param service_sid: The SID of the Service that the resource is associated with + :returns: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v1.service.channel.ChannelList - :rtype: twilio.rest.chat.v1.service.channel.ChannelList + def delete(self) -> bool: """ - super(ChannelList, self).__init__(version) + Deletes the ChannelInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Channels'.format(**self._solution) - def create(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset, type=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the ChannelInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance - :returns: The created ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: """ - data = values.of({ - 'FriendlyName': friendly_name, - 'UniqueName': unique_name, - 'Attributes': attributes, - 'Type': type, - }) + Deletes the ChannelInstance with HTTP info - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() - def stream(self, type=values.unset, limit=None, page_size=None): + async def delete_with_http_info_async(self) -> ApiResponse: """ - 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. + Asynchronous coroutine that deletes the ChannelInstance with HTTP info - :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) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.ChannelInstance] + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(type=type, page_size=limits['page_size'], ) + def fetch(self) -> "ChannelInstance": + """ + Fetch the ChannelInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, type=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelInstance": + """ + Asynchronous coroutine to 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 await self._proxy.fetch_async() - def page(self, type=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of ChannelInstance records from the API. - Request is executed immediately + Fetch the ChannelInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Type': serialize.map(type, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance with HTTP info - return ChannelPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of ChannelInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Update the ChannelInstance - :returns: Page of ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelPage + :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 """ - 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) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Asynchronous coroutine to update the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. - def get(self, sid): + :returns: The updated ChannelInstance """ - Constructs a ChannelContext + return await self._proxy.update_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) - :param sid: The unique string that identifies the resource + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Constructs a ChannelContext + Asynchronous coroutine to update the ChannelInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + return self._proxy.invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + return self._proxy.members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages - def __repr__(self): + 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) + + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of ChannelInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.service.channel.ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + def delete(self) -> bool: """ - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the ChannelInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the ChannelInstance and return response metadata -class ChannelContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the ChannelContext - :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 + headers = values.of({}) - :returns: twilio.rest.chat.v1.service.channel.ChannelContext - :rtype: twilio.rest.chat.v1.service.channel.ChannelContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(ChannelContext, self).__init__(version) + Asynchronous coroutine that deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance and return response metadata - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Channels/{sid}'.format(**self._solution) - # Dependents - self._members = None - self._messages = None - self._invites = None + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def fetch(self): + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: """ Fetch the ChannelInstance + :returns: The fetched ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + :returns: The fetched ChannelInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the ChannelInstance + Asynchronous coroutine to fetch the ChannelInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + } + ) + headers = values.of({}) - def update(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: """ Update the ChannelInstance - :param 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._update( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :returns: The updated ChannelInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) return ChannelInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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) + - def __repr__(self): +class ChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: + """ + Build an instance of ChannelInstance + + :param payload: Payload response from the API + """ + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class ChannelInstance(InstanceResource): - """ """ +class ChannelList(ListResource): - class ChannelType(object): - PUBLIC = "public" - PRIVATE = "private" + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ChannelList - 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'), - } + :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. - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + """ + super().__init__(version) - @property - def _proxy(self): + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Channels".format(**self._solution) + + def _create( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> tuple: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Internal helper for create operation - :returns: ChannelContext for this ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelContext + Returns: + tuple: (payload, status_code, headers) """ - if self._context is None: - self._context = ChannelContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context - @property - def sid(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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Create the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + + :returns: The created ChannelInstance """ - return self._properties['sid'] + payload, _, _ = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def account_sid(self): + def create_with_http_info( + 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, + ) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Create the ChannelInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['account_sid'] + payload, status_code, headers = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def service_sid(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, + ) -> tuple: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['service_sid'] - @property - def friendly_name(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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 string that you assigned to describe the resource - :rtype: unicode + Asynchronously create the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + + :returns: The created ChannelInstance """ - return self._properties['friendly_name'] + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def unique_name(self): + async def create_with_http_info_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, + ) -> ApiResponse: """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + Asynchronously create the ChannelInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['unique_name'] + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def attributes(self): + def stream( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: """ - :returns: The JSON string that stores application-specific data - :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['attributes'] + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) - @property - def type(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 visibility of the channel. Can be: `public` or `private` - :rtype: ChannelInstance.ChannelType + 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['type'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) - @property - def date_created(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + Streams ChannelInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + type=type, page_size=limits["page_size"] + ) - @property - def date_updated(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + Asynchronously streams ChannelInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + type=type, page_size=limits["page_size"] + ) - @property - def created_by(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: """ - :returns: The identity of the User that created 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 self._properties['created_by'] - @property - def members_count(self): + 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]: """ - :returns: The number of Members in the Channel - :rtype: unicode + Asynchronously lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['members_count'] - @property - def messages_count(self): + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The number of Messages in the Channel - :rtype: unicode + Lists ChannelInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers """ - return self._properties['messages_count'] + generator, status_code, headers = self.stream_with_http_info( + type=type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def url(self): + async def list_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The absolute URL of the Channel resource - :rtype: unicode + Asynchronously lists ChannelInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers """ - return self._properties['url'] + generator, status_code, headers = await self.stream_with_http_info_async( + type=type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def links(self): + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: """ - :returns: Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel - :rtype: unicode + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance """ - return self._properties['links'] + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def fetch(self): + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, solution=self._solution) + + async def page_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: """ - Fetch the ChannelInstance + Asynchronously 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, solution=self._solution) - def delete(self): + def page_with_http_info( + 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, + ) -> ApiResponse: """ - Deletes the ChannelInstance + Retrieve a single page with response metadata - :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: ApiResponse with ChannelPage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ChannelPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - 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, solution=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, solution=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 21d8dacc8a..d88124ec63 100644 --- a/twilio/rest/chat/v1/service/channel/invite.py +++ b/twilio/rest/chat/v1/service/channel/invite.py @@ -1,448 +1,985 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 + return self._proxy.delete() - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The Role assigned to the new member + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance - :returns: The created InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + + :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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance with HTTP info - return InviteInstance( - 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: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.invite.InviteInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "InviteInstance": + """ + Fetch the InviteInstance - page = self.page(identity=identity, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched InviteInstance + """ + return self._proxy.fetch() - def list(self, identity=values.unset, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to 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. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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 """ - return list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of InviteInstance records from the API. - Request is executed immediately + Fetch the InviteInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance with HTTP info - return InvitePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of InviteInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InvitePage + :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 InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the InviteContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to fetch the resource from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the resource to fetch belongs to. + :param sid: The Twilio-provided string that uniquely identifies the Invite resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Invites/{sid}".format( + **self._solution + ) ) - return InvitePage(self._version, response, self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation - def get(self, sid): + Returns: + tuple: (success_boolean, status_code, headers) """ - Constructs a InviteContext - :param sid: The unique string that identifies the resource + headers = values.of({}) - :returns: twilio.rest.chat.v1.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteContext + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return InviteContext( + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + payload, _, _ = self._fetch() + 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 __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a InviteContext + Fetch the InviteInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return InviteContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class InvitePage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> InviteInstance: """ - Initialize the InvitePage + Asynchronous coroutine to fetch the InviteInstance + - :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 + :returns: The fetched InviteInstance + """ + payload, _, _ = await self._fetch_async() + 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 + async def fetch_with_http_info_async(self) -> ApiResponse: """ - super(InvitePage, self).__init__(version, response) + Asynchronous coroutine to fetch the InviteInstance and return response metadata - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of InviteInstance + payload, status_code, headers = await self._fetch_async() + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.chat.v1.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + :returns: Machine friendly representation """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: + """ + Build an instance of InviteInstance + + :param payload: Payload response from the API + """ + return InviteInstance( self._version, payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + 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 + ) -> tuple: """ - Fetch the InviteInstance + Internal helper for create operation - :returns: The fetched InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new member. + + :returns: The created InviteInstance + """ + payload, _, _ = self._create(identity=identity, role_sid=role_sid) 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): + def create_with_http_info( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: """ - Deletes the InviteInstance + Create the InviteInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: """ - Provide a friendly representation + Internal async helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - 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"}) -class InviteInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, payload, service_sid, channel_sid, sid=None): + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: """ - Initialize the InviteInstance + Asynchronously create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new member. - :returns: twilio.rest.chat.v1.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + :returns: The created InviteInstance """ - super(InviteInstance, self).__init__(version) + payload, _, _ = await self._create_async(identity=identity, role_sid=role_sid) + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - # 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'), - } + async def create_with_http_info_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the InviteInstance and return response metadata - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + :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. - @property - def _proxy(self): + :returns: ApiResponse with instance, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, status_code, headers = await self._create_async( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: InviteContext for this InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteContext + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[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 + 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 sid(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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InviteInstance]: """ - return self._properties['sid'] + 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 account_sid(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 """ - :returns: The SID of the Account that created the resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['account_sid'] + Streams InviteInstance and returns headers from first page - @property - def channel_sid(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The SID of the Channel the new resource belongs to - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['channel_sid'] + Asynchronously streams InviteInstance and returns headers from first page - @property - def service_sid(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - return self._properties['service_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. - @property - def identity(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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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 identifies the resource's User - :rtype: unicode + + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - return self._properties['identity'] + 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 date_created(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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_created'] + Lists InviteInstance and returns headers from first page - @property - def date_updated(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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously lists InviteInstance and returns headers from first page - @property - def role_sid(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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - :returns: The SID of the Role assigned to the member - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['role_sid'] + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately - @property - def created_by(self): + :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 """ - :returns: The identity of the User that created the invite - :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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, solution=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: """ - return self._properties['created_by'] + Asynchronously retrieve a single page of InviteInstance records from the API. + Request is executed immediately - @property - def url(self): + :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 """ - :returns: The absolute URL of the Invite 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 InvitePage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['url'] + Retrieve a single page with response metadata + + + :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 - def fetch(self): + :returns: ApiResponse with InvitePage, status code, and headers """ - Fetch the InviteInstance + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: The fetched InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with InvitePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> InvitePage: """ - return self._proxy.fetch() + Retrieve a specific page of InviteInstance 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 InviteInstance """ - Deletes the InviteInstance + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, solution=self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def get_page_async(self, target_url: str) -> InvitePage: """ - return self._proxy.delete() + Asynchronously retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: The Twilio-provided string that uniquely identifies the Invite resource to fetch. + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: The Twilio-provided string that uniquely identifies the Invite resource to fetch. + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 d8ed7b6c58..392847cb06 100644 --- a/twilio/rest/chat/v1/service/channel/member.py +++ b/twilio/rest/chat/v1/service/channel/member.py @@ -1,496 +1,1217 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class MemberList(ListResource): - """ """ +class MemberInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Member resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Member resource. + :ivar channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) for the member. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar identity: The application-defined string that uniquely identifies the resource's [User](https://www.twilio.com/docs/api/chat/rest/users) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the member. + :ivar last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) in the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) that the Member has read. + :ivar last_consumption_timestamp: The ISO 8601 timestamp string that represents the date-time of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) read event for the Member within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + :ivar url: The absolute URL of the Member resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } - def __init__(self, version, service_sid, channel_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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MemberInstance with HTTP info - 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: ApiResponse with success boolean, status code, and headers """ - 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.delete_with_http_info() - :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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.member.MemberInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(identity=identity, page_size=limits['page_size'], ) + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, identity=values.unset, limit=None, page_size=None): + :returns: The fetched MemberInstance """ - Lists MemberInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return 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. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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) -> "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 """ - return list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of MemberInstance records from the API. - Request is executed immediately + Fetch the MemberInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance with HTTP info - return MemberPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of MemberInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance - :returns: Page of MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberPage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, ) - return MemberPage(self._version, response, self._solution) + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> "MemberInstance": + """ + Asynchronous coroutine to update the MemberInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). - def get(self, sid): + :returns: The updated MemberInstance """ - Constructs a MemberContext + return await self._proxy.update_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the MemberInstance with HTTP info - :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) 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.MemberContext - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + :returns: ApiResponse with instance, status code, and headers """ - return MemberContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + return self._proxy.update_with_http_info( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Constructs a MemberContext + Asynchronous coroutine to update the MemberInstance with HTTP info - :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) 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.MemberContext - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + :returns: ApiResponse with instance, status code, and headers """ - return MemberContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + return await self._proxy.update_with_http_info_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, ) - 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 MemberPage(Page): - """ """ +class MemberContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - 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 unique ID of the Channel for the member + Initialize the MemberContext - :returns: twilio.rest.chat.v1.service.channel.member.MemberPage - :rtype: twilio.rest.chat.v1.service.channel.member.MemberPage + :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(MemberPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of MemberInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.service.channel.member.MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + def delete(self) -> bool: """ - return MemberInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + Deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MemberInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the MemberInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance and return response metadata -class MemberContext(InstanceContext): - """ """ - def __init__(self, version, service_sid, channel_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the MemberContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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 unique ID of the channel the member belongs to - :param sid: The unique string that identifies the resource + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.chat.v1.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + Returns: + tuple: (payload, status_code, headers) """ - super(MemberContext, 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}/Members/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> MemberInstance: """ Fetch the MemberInstance + :returns: The fetched MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + payload, _, _ = await self._fetch_async() 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"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the MemberInstance + Asynchronous coroutine to fetch the MemberInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, role_sid=values.unset, - last_consumed_message_index=values.unset): + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> 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 + :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 - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance """ - data = values.of({'RoleSid': role_sid, 'LastConsumedMessageIndex': last_consumed_message_index, }) + payload, _, _ = self._update( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the MemberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :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 + """ + payload, _, _ = await self._update_async( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) 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"], + sid=self._solution["sid"], ) - def __repr__(self): + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide 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 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'), - } +class MemberPage(Page): - # Context - self._context = None + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: + """ + Build an instance of MemberInstance + + :param payload: Payload response from the API + """ + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MemberList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MemberList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + :param channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the members to read belong to. Can be the Channel resource's `sid` or `unique_name` value. + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "channel_sid": channel_sid, } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) - @property - def _proxy(self): + def _create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Internal helper for create operation - :returns: MemberContext for this MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + Returns: + tuple: (payload, status_code, headers) """ - 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 - @property - def sid(self): + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Create the MemberInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + + :returns: The created MemberInstance """ - return self._properties['sid'] + payload, _, _ = self._create(identity=identity, role_sid=role_sid) + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def account_sid(self): + def create_with_http_info( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Create the MemberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['account_sid'] + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def channel_sid(self): + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: """ - :returns: The unique ID of the Channel for the member - :rtype: unicode + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['channel_sid'] - @property - def service_sid(self): + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + Asynchronously create the MemberInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + + :returns: The created MemberInstance """ - return self._properties['service_sid'] + payload, _, _ = await self._create_async(identity=identity, role_sid=role_sid) + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def identity(self): + async def create_with_http_info_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: """ - :returns: The string that identifies the resource's User - :rtype: unicode + Asynchronously create the MemberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['identity'] + payload, status_code, headers = await self._create_async( + identity=identity, role_sid=role_sid + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def date_created(self): + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + Streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) - @property - def date_updated(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + Asynchronously streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) - @property - def role_sid(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Role assigned to the member - :rtype: unicode + Streams MemberInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['role_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) - @property - def last_consumed_message_index(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The index of the last Message that the Member has read within the Channel - :rtype: unicode + Asynchronously streams MemberInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['last_consumed_message_index'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) - @property - def last_consumption_timestamp(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - :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 + 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 self._properties['last_consumption_timestamp'] - @property - def url(self): + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - :returns: The absolute URL of the Member resource - :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 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 self._properties['url'] - def fetch(self): + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Fetch the MemberInstance + Lists MemberInstance and returns headers from first page - :returns: The fetched MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + + :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: ApiResponse with list of instances, status code, and headers """ - return self._proxy.fetch() + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - def delete(self): + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Deletes the MemberInstance + Asynchronously lists MemberInstance and returns headers from first page - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :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: ApiResponse with list of instances, status code, and headers """ - return self._proxy.delete() + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - def update(self, role_sid=values.unset, - last_consumed_message_index=values.unset): + 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: """ - Update the MemberInstance + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately - :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 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: The updated MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + :returns: Page of MemberInstance """ - return self._proxy.update( - role_sid=role_sid, - last_consumed_message_index=last_consumed_message_index, + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, solution=self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with MemberPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with MemberPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> MemberPage: + """ + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> MemberPage: + """ + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: The Twilio-provided string that uniquely identifies the Member resource to update. + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: The Twilio-provided string that uniquely identifies the Member resource to update. + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 b0ea030c49..11824c42ed 100644 --- a/twilio/rest/chat/v1/service/channel/message.py +++ b/twilio/rest/chat/v1/service/channel/message.py @@ -1,513 +1,1242 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class MessageList(ListResource): - """ """ +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + """ + :ivar sid: The unique string that we created to identify the Message resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Message resource. + :ivar attributes: The JSON string that stores application-specific data. **Note** If this property has been assigned a value, it's only displayed in a FETCH action that returns a single resource; otherwise, it's null. If the attributes have not been set, `{}` is returned. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar to: The SID of the [Channel](https://www.twilio.com/docs/chat/api/channels) that the message was sent to. + :ivar channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the Message resource belongs to. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar was_edited: Whether the message has been edited since it was created. + :ivar _from: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the message's author. The default value is `system`. + :ivar body: The content of the message. + :ivar index: The index of the message within the [Channel](https://www.twilio.com/docs/chat/api/channels). + :ivar url: The absolute URL of the Message resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.service_sid: Optional[str] = payload.get("service_sid") + self.to: Optional[str] = payload.get("to") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.was_edited: Optional[bool] = payload.get("was_edited") + self._from: Optional[str] = payload.get("from") + self.body: Optional[str] = payload.get("body") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } - def __init__(self, version, service_sid, channel_sid): + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": """ - Initialize the MessageList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The 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: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v1.service.channel.message.MessageList - :rtype: twilio.rest.chat.v1.service.channel.message.MessageList + def delete(self) -> bool: """ - super(MessageList, self).__init__(version) + Deletes the MessageInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'channel_sid': channel_sid, } - self._uri = '/Services/{service_sid}/Channels/{channel_sid}/Messages'.format(**self._solution) - def create(self, body, from_=values.unset, attributes=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the MessageInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance - :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 await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info - 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: ApiResponse with success boolean, status code, and headers """ - Streams MessageInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + return self._proxy.delete_with_http_info() - :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) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.message.MessageInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(order=order, page_size=limits['page_size'], ) + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, order=values.unset, limit=None, page_size=None): + :returns: The fetched MessageInstance """ - Lists MessageInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + 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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately + Fetch the MessageInstance with HTTP info - :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.v1.service.channel.message.MessagePage + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Order': order, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info - return MessagePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + 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 self._proxy.update( + body=body, + attributes=attributes, ) - return MessagePage(self._version, response, self._solution) + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance - def get(self, sid): + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MessageInstance """ - Constructs a MessageContext + return await self._proxy.update_async( + body=body, + attributes=attributes, + ) + + def update_with_http_info( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return MessageContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + return self._proxy.update_with_http_info( + body=body, + attributes=attributes, ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Constructs a MessageContext + Asynchronous coroutine to update the MessageInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return MessageContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + return await self._proxy.update_with_http_info_async( + body=body, + attributes=attributes, ) - 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, service_sid: str, channel_sid: str, sid: str): """ - Initialize the MessagePage - - :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 + Initialize the MessageContext - :returns: twilio.rest.chat.v1.service.channel.message.MessagePage - :rtype: twilio.rest.chat.v1.service.channel.message.MessagePage + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to update the resource from. + :param channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the message belongs to. Can be the Channel's `sid` or `unique_name`. + :param sid: The Twilio-provided string that uniquely identifies the Message resource to update. """ - super(MessagePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of MessageInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.service.channel.message.MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + def delete(self) -> bool: """ - return MessageInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + Deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessageInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + 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 '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance and return response metadata -class MessageContext(InstanceContext): - """ """ - def __init__(self, version, service_sid, channel_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the MessageContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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 unique ID of the Channel the message to fetch belongs to - :param sid: The unique string that identifies the resource + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.chat.v1.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext + Returns: + tuple: (payload, status_code, headers) """ - 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) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: """ Fetch the MessageInstance + :returns: The fetched MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the MessageInstance + Asynchronous coroutine to fetch the MessageInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for update operation - def update(self, body=values.unset, attributes=values.unset): + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ 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 + :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 - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance """ - data = values.of({'Body': body, 'Attributes': attributes, }) + payload, _, _ = self._update(body=body, attributes=attributes) + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(body=body, attributes=attributes) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MessageInstance + """ + payload, _, _ = await self._update_async(body=body, attributes=attributes) 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"], + ) + + async def update_with_http_info_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + body=body, attributes=attributes + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class MessageInstance(InstanceResource): - """ """ +class MessagePage(Page): - class OrderType(object): - ASC = "asc" - DESC = "desc" + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance - 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 payload: Payload response from the API + """ + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - # Context - self._context = None + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MessageList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + :param channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the message to read belongs to. Can be the Channel's `sid` or `unique_name`. + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - '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, + ) -> tuple: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Internal helper for create operation - :returns: MessageContext for this MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext + Returns: + tuple: (payload, status_code, headers) """ - 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 - @property - def sid(self): + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Create the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param from_: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The created MessageInstance """ - return self._properties['sid'] + payload, _, _ = self._create(body=body, from_=from_, attributes=attributes) + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def account_sid(self): + def create_with_http_info( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Create the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['account_sid'] + payload, status_code, headers = self._create( + body=body, from_=from_, attributes=attributes + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def attributes(self): + async def _create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: """ - :returns: The JSON string that stores application-specific data - :rtype: unicode + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['attributes'] - @property - def service_sid(self): + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + Asynchronously create the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param from_: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The created MessageInstance """ - return self._properties['service_sid'] + payload, _, _ = await self._create_async( + body=body, from_=from_, attributes=attributes + ) + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def to(self): + async def create_with_http_info_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: """ - :returns: The SID of the Channel that the message was sent to - :rtype: unicode + Asynchronously create the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['to'] + payload, status_code, headers = await self._create_async( + body=body, from_=from_, attributes=attributes + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def channel_sid(self): + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: """ - :returns: The unique ID of the Channel the Message resource belongs to - :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['channel_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) - @property - def date_created(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 RFC 2822 date and time in GMT when the resource was created - :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_created'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) - @property - def date_updated(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + Streams MessageInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + order=order, page_size=limits["page_size"] + ) - @property - def was_edited(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: Whether the message has been edited since it was created - :rtype: bool + Asynchronously streams MessageInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['was_edited'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + order=order, page_size=limits["page_size"] + ) - @property - def from_(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - :returns: The identity of the message's author - :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 self._properties['from_'] - @property - def body(self): + 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 self._properties['body'] - @property - def index(self): + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The index of the message within the Channel - :rtype: unicode + Lists MessageInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers """ - return self._properties['index'] + generator, status_code, headers = self.stream_with_http_info( + order=order, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def url(self): + async def list_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The absolute URL of the Message resource - :rtype: unicode + Asynchronously lists MessageInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers """ - return self._properties['url'] + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - def fetch(self): + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: """ - Fetch the MessageInstance + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately - :returns: The fetched MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + :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._proxy.fetch() + 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, solution=self._solution) - def delete(self): + 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: """ - Deletes the MessageInstance + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._proxy.delete() + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def update(self, body=values.unset, attributes=values.unset): + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: """ - Update the MessageInstance + Retrieve a single page with response metadata - :param unicode body: The message to send to the channel - :param unicode attributes: A valid JSON string that contains application-specific data - :returns: The updated MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + :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: ApiResponse with MessagePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with MessagePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: The Twilio-provided string that uniquely identifies the Message resource to update. """ - return 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 __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: The Twilio-provided string that uniquely identifies the Message resource to update. + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 97adb36be1..a17f74eb7c 100644 --- a/twilio/rest/chat/v1/service/role.py +++ b/twilio/rest/chat/v1/service/role.py @@ -1,442 +1,1086 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class RoleList(ListResource): - """ """ +class RoleInstance(InstanceResource): + + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" + + """ + :ivar sid: The unique string that we created to identify the Role resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Role resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar permissions: An array of the permissions the role has been granted, formatted as a JSON string. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the Role resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } - def __init__(self, version, service_sid): + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": """ - Initialize the RoleList + 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: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v1.service.role.RoleList - :rtype: twilio.rest.chat.v1.service.role.RoleList + def delete(self) -> bool: """ - super(RoleList, self).__init__(version) + Deletes the RoleInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Roles'.format(**self._solution) - def create(self, friendly_name, type, permission): + :returns: True if delete succeeds, False otherwise """ - Create the RoleInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance - :returns: The created RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Type': type, - 'Permission': serialize.map(permission, lambda e: e), - }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.role.RoleInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.role.RoleInstance] + + :returns: The fetched RoleInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of RoleInstance records from the API. - Request is executed immediately + Fetch the RoleInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info - return RolePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of RoleInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance - :param str target_url: API-generated URL for the requested results page + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RolePage + :returns: The updated RoleInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + permission=permission, ) - return RolePage(self._version, response, self._solution) + async def update_async(self, permission: List[str]) -> "RoleInstance": + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. - def get(self, sid): + :returns: The updated RoleInstance """ - Constructs a RoleContext + return await self._proxy.update_async( + permission=permission, + ) - :param sid: The unique string that identifies the resource + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + permission=permission, + ) - def __call__(self, sid): + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: """ - Constructs a RoleContext + Asynchronous coroutine to update the RoleInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_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) -> tuple: """ - Build an instance of RoleInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.service.role.RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + def delete(self) -> bool: """ - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the RoleInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the RoleInstance and return response metadata -class RoleContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the RoleContext + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :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 + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.service.role.RoleContext - :rtype: twilio.rest.chat.v1.service.role.RoleContext + async def delete_async(self) -> bool: """ - super(RoleContext, self).__init__(version) + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance and return response metadata - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Roles/{sid}'.format(**self._solution) - def fetch(self): + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: """ Fetch the RoleInstance + :returns: The fetched RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + :returns: The fetched RoleInstance + """ + payload, _, _ = await self._fetch_async() return RoleInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the RoleInstance + Asynchronous coroutine to fetch the RoleInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, permission: List[str]) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for update operation - def update(self, permission): + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, permission: List[str]) -> RoleInstance: """ 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._update(permission=permission) + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, permission: List[str]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Accept"] = "application/json" + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The updated RoleInstance + """ + payload, _, _ = await self._update_async(permission=permission) 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"], + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 - :returns: twilio.rest.chat.v1.service.role.RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + 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 "" + + +class RoleList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the RoleList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/Roles".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - 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 - :rtype: twilio.rest.chat.v1.service.role.RoleContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: """ - if self._context is None: - self._context = RoleContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the RoleInstance - @property - def 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 unique string that identifies the resource - :rtype: unicode + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: """ - return self._properties['sid'] + Create the RoleInstance and return response metadata - @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: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Account that created the resource - :rtype: unicode + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for create operation - @property - def service_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: """ - return self._properties['service_sid'] + Asynchronously create the RoleInstance - @property - def friendly_name(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 string that you assigned to describe the resource - :rtype: unicode + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: """ - return self._properties['friendly_name'] + Asynchronously create the RoleInstance and return response metadata - @property - def type(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: ApiResponse with instance, status code, and headers """ - :returns: The type of role - :rtype: RoleInstance.RoleType + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: """ - return self._properties['type'] + 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 permissions(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 array of the permissions the role has been granted - :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['permissions'] + 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 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 = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_created'] + Streams RoleInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :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_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_updated'] + Asynchronously streams RoleInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The absolute URL of the Role resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: """ - return self._properties['url'] + 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) - def fetch(self): + :returns: list that will contain up to limit results """ - Fetch the RoleInstance - :returns: The fetched RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + return 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._proxy.fetch() + 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) - def delete(self): + :returns: list that will contain up to limit results """ - Deletes the RoleInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.delete() + Lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - def update(self, permission): + :returns: ApiResponse with list of instances, status code, and headers """ - Update the RoleInstance + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoleInstance and returns headers from first page - :param unicode permission: A permission the role should have - :returns: The updated RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.update(permission, ) + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The Twilio-provided string that uniquely identifies the Role resource to update. + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The Twilio-provided string that uniquely identifies the Role resource to update. + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 e2b596f4a1..69a785ce4f 100644 --- a/twilio/rest/chat/v1/service/user/__init__.py +++ b/twilio/rest/chat/v1/service/user/__init__.py @@ -1,521 +1,1244 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): - """ """ +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") - def __init__(self, version, service_sid): + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": """ - Initialize the UserList + 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: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v1.service.user.UserList - :rtype: twilio.rest.chat.v1.service.user.UserList + def delete(self) -> bool: """ - super(UserList, self).__init__(version) + Deletes the UserInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Users'.format(**self._solution) - def create(self, identity, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the UserInstance + 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 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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance - :returns: The created UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'Identity': identity, - 'RoleSid': role_sid, - 'Attributes': attributes, - 'FriendlyName': friendly_name, - }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance - :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 await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of UserInstance records from the API. - Request is executed immediately + Fetch the UserInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info - return UserPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of UserInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance - :returns: Page of UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserPage + :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 """ - 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) + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. - def get(self, sid): + :returns: The updated UserInstance """ - Constructs a UserContext + return await self._proxy.update_async( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return UserContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Constructs a UserContext + Asynchronous coroutine to update the UserInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return UserContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) - def __repr__(self): + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + return self._proxy.user_channels + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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) -> tuple: """ - Build an instance of UserInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.service.user.UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + def delete(self) -> bool: """ - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the UserInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the UserInstance and return response metadata -class UserContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the UserContext + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :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 + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.service.user.UserContext - :rtype: twilio.rest.chat.v1.service.user.UserContext + async def delete_async(self) -> bool: """ - super(UserContext, self).__init__(version) + Asynchronous coroutine that deletes the UserInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Users/{sid}'.format(**self._solution) - # Dependents - self._user_channels = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success - def fetch(self): + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: """ Fetch the UserInstance + :returns: The fetched UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() 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_with_http_info_async(self) -> ApiResponse: """ - Deletes the UserInstance + Asynchronous coroutine to fetch the UserInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for update operation - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: """ Update the UserInstance - :param 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._update( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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, + ) -> tuple: + """ + Internal async helper for update operation + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + payload, _, _ = await self._update_async( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) 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"], + ) + + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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'), +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/Users".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + 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, + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: UserContext for this UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - if self._context is None: - self._context = UserContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the UserInstance - @property - def sid(self): + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = self._create( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['sid'] + Create the UserInstance and return response metadata - @property - def account_sid(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: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Account that created the resource - :rtype: unicode + payload, status_code, headers = self._create( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for create operation - @property - def service_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['service_sid'] + Asynchronously create the UserInstance - @property - def attributes(self): + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance """ - :returns: The JSON string that stores application-specific data - :rtype: unicode + payload, _, _ = await self._create_async( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['attributes'] + Asynchronously create the UserInstance and return response metadata - @property - def friendly_name(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: ApiResponse with instance, status code, and headers """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + payload, status_code, headers = await self._create_async( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: """ - return self._properties['friendly_name'] + 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 role_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 assigned to the user - :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[UserInstance]: """ - return self._properties['role_sid'] + 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 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 string that identifies the resource's User - :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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['identity'] + Streams UserInstance and returns headers from first page - @property - def is_online(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: Whether the User is actively connected to the Service instance and online - :rtype: bool + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['is_online'] + Asynchronously streams UserInstance and returns headers from first page - @property - def is_notifiable(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: Whether the User has a potentially valid Push Notification registration for the Service instance - :rtype: bool + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: """ - return self._properties['is_notifiable'] + 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 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[UserInstance]: """ - return self._properties['date_created'] + 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 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 RFC 2822 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Lists UserInstance and returns headers from first page - @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: ApiResponse with list of instances, status code, and headers """ - :returns: The number of Channels this User is a Member of - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['joined_channels_count'] + Asynchronously lists UserInstance and returns headers from first page - @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: ApiResponse with list of instances, status code, and headers """ - :returns: The absolute URLs of the Channel and Binding resources related to the user - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: """ - return self._properties['url'] + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - def fetch(self): + :returns: Page of UserInstance """ - Fetch 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.fetch() + Retrieve a single page with response metadata + - def delete(self): + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers """ - Deletes the UserInstance + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.delete() + Asynchronously retrieve a single page with response metadata - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers """ - Update the UserInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :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 + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: The updated UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> UserPage: """ - return self._proxy.update(role_sid=role_sid, attributes=attributes, friendly_name=friendly_name, ) + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately - @property - def user_channels(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance """ - Access the user_channels + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, solution=self._solution) - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelList + async def get_page_async(self, target_url: str) -> UserPage: """ - return self._proxy.user_channels + 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, solution=self._solution) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The Twilio-provided string that uniquely identifies the User resource to update. + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The Twilio-provided string that uniquely identifies the User resource to update. + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 7e1c7f1e4c..604cbddec5 100644 --- a/twilio/rest/chat/v1/service/user/user_channel.py +++ b/twilio/rest/chat/v1/service/user/user_channel.py @@ -1,273 +1,496 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class UserChannelInstance(InstanceResource): + + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOT_PARTICIPATING = "not_participating" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the User Channel resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the resource belongs to. + :ivar member_sid: The SID of a [Member](https://www.twilio.com/docs/api/chat/rest/members) that represents the User on the Channel. + :ivar status: + :ivar last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) in the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) that the Member has read. + :ivar unread_messages_count: The number of unread Messages in the Channel for the User. Note that retrieving messages on a client endpoint does not mean that messages are consumed or read. See [Consumption Horizon feature](/docs/api/chat/guides/consumption-horizon) to learn how to mark messages as consumed. + :ivar links: The absolute URLs of the [Members](https://www.twilio.com/docs/chat/api/members), [Messages](https://www.twilio.com/docs/chat/api/messages) , [Invites](https://www.twilio.com/docs/chat/api/invites) and, if it exists, the last [Message](https://www.twilio.com/docs/chat/api/messages) for the Channel. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], service_sid: str, user_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.member_sid: Optional[str] = payload.get("member_sid") + self.status: Optional["UserChannelInstance.ChannelStatus"] = payload.get( + "status" + ) + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: + """ + Build an instance of UserChannelInstance + + :param payload: Payload response from the API + """ + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class UserChannelList(ListResource): - """ """ - def __init__(self, version, service_sid, user_sid): + def __init__(self, version: Version, service_sid: str, user_sid: str): """ Initialize the UserChannelList - :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 + :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: twilio.rest.chat.v1.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelList """ - super(UserChannelList, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Channels".format( + **self._solution + ) - def stream(self, limit=None, page_size=None): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserChannelInstance]: """ Streams UserChannelInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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.chat.v1.service.user.user_channel.UserChannelInstance] """ 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'], limits['page_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[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. + 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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.chat.v1.service.user.user_channel.UserChannelInstance] """ - 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Retrieve a single page of UserChannelInstance records from the API. - Request is executed immediately + Streams UserChannelInstance and returns headers from first page - :param str page_token: PageToken provided by the API - :param int page_number: 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.v1.service.user.user_channel.UserChannelPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - return UserChannelPage(self._version, response, self._solution) + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - def get_page(self, target_url): + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Retrieve a specific page of UserChannelInstance records from the API. - Request is executed immediately + Asynchronously streams UserChannelInstance and returns headers from first page - :param str target_url: API-generated URL for the requested results page - :returns: Page of UserChannelInstance - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelPage + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] ) - return UserChannelPage(self._version, response, self._solution) + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - def __repr__(self): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: """ - Provide a friendly representation + 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 '' + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) -class UserChannelPage(Page): - """ """ + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Asynchronously lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - def __init__(self, version, response, 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) + + :returns: list that will contain up to limit results """ - 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 unique string that identifies the resource + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelPage - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelPage + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - super(UserChannelPage, self).__init__(version, response) + Lists UserChannelInstance and returns headers from first page - # Path Solution - self._solution = solution - def get_instance(self, payload): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - Build an instance of UserChannelInstance + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserChannelInstance and returns headers from first page + - :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: ApiResponse with list of instances, status code, and headers """ - return UserChannelInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - def __repr__(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, + ) -> UserChannelPage: """ - Provide a friendly representation + Retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately - :returns: Machine friendly representation - :rtype: str + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance """ - return '' + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class UserChannelInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - class ChannelStatus(object): - JOINED = "joined" - INVITED = "invited" - NOT_PARTICIPATING = "not_participating" + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, solution=self._solution) - def __init__(self, version, payload, service_sid, user_sid): + async def 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: """ - Initialize the UserChannelInstance + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance + :param page_token: PageToken provided by the API + :param page_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 """ - super(UserChannelInstance, self).__init__(version) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - # 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'), - } + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'user_sid': user_sid, } + 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'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, solution=self._solution) - @property - def service_sid(self): + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + Retrieve a single page with response metadata - @property - def channel_sid(self): - """ - :returns: The SID of the Channel the resource belongs to - :rtype: unicode - """ - return self._properties['channel_sid'] - @property - def member_sid(self): - """ - :returns: The SID of the User as a Member in the Channel - :rtype: unicode - """ - return self._properties['member_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 status(self): - """ - :returns: The status of the User on the Channel - :rtype: UserChannelInstance.ChannelStatus + :returns: ApiResponse with UserChannelPage, status code, and headers """ - return self._properties['status'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def last_consumed_message_index(self): + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The index of the last Message in the Channel the Member has read - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserChannelPage, status code, and headers """ - return self._properties['last_consumed_message_index'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def unread_messages_count(self): + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> UserChannelPage: """ - :returns: The number of unread Messages in the Channel for the User - :rtype: unicode + 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['unread_messages_count'] + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, solution=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, solution=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 9733c1ebce..40c972a9c2 100644 --- a/twilio/rest/chat/v2/credential.py +++ b/twilio/rest/chat/v2/credential.py @@ -1,431 +1,907 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the Credential resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Credential resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Credential resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } - def __init__(self, version): + self._context: Optional[CredentialContext] = None + + @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 + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v2.credential.CredentialList - :rtype: twilio.rest.chat.v2.credential.CredentialList + def delete(self) -> bool: """ - super(CredentialList, self).__init__(version) + Deletes the CredentialInstance - # Path Solution - self._solution = {} - self._uri = '/Credentials'.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.chat.v2.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.credential.CredentialInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "CredentialInstance": """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + 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 self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance - return CredentialPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched CredentialInstance """ - Retrieve a specific page of CredentialInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info - :returns: Page of CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info - return CredentialPage(self._version, response, self._solution) - 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: ApiResponse with instance, status code, and headers """ - Create the CredentialInstance + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance - :param 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 + :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 created CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + :returns: The updated CredentialInstance """ - data = values.of({ - 'Type': type, - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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 - return CredentialInstance(self._version, payload, ) + :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(self, sid): + :returns: The updated CredentialInstance """ - Constructs a CredentialContext + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - :param sid: The SID of the Credential resource to fetch + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + :returns: ApiResponse with instance, status code, and headers """ - return CredentialContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - def __call__(self, sid): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Constructs a CredentialContext + Asynchronous coroutine to update the CredentialInstance with HTTP info - :param sid: The SID of the Credential resource to fetch + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + :returns: ApiResponse with instance, status code, and headers """ - return CredentialContext(self._version, sid=sid, ) + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialPage(Page): - """ """ +class CredentialContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the CredentialPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the CredentialContext - :returns: twilio.rest.chat.v2.credential.CredentialPage - :rtype: twilio.rest.chat.v2.credential.CredentialPage + :param version: Version that contains the resource + :param sid: The SID of the Credential resource to update. """ - super(CredentialPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of CredentialInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v2.credential.CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + def delete(self) -> bool: """ - return CredentialInstance(self._version, payload, ) + Deletes the CredentialInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the CredentialInstance and return response metadata -class CredentialContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the CredentialContext - :param Version version: Version that contains the resource - :param sid: The SID of the Credential resource to fetch + headers = values.of({}) - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(CredentialContext, self).__init__(version) + Asynchronous coroutine that deletes the CredentialInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: """ Fetch the CredentialInstance + :returns: The fetched CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance and return response metadata - 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): + :returns: ApiResponse with instance, status code, and headers """ - Update the CredentialInstance + payload, status_code, headers = self._fetch() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :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 + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: The updated CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ - 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, ) + headers = values.of({}) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CredentialInstance: """ - Deletes the CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched CredentialInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, _, _ = await self._fetch_async() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the CredentialInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + payload, status_code, headers = await self._fetch_async() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + Returns: + tuple: (payload, status_code, headers) + """ -class CredentialInstance(InstanceResource): - """ """ + 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({}) - class PushService(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - def __init__(self, version, payload, sid=None): + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - Initialize the CredentialInstance + Update the CredentialInstance - :returns: twilio.rest.chat.v2.credential.CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance """ - super(CredentialInstance, self).__init__(version) + payload, _, _ = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CredentialInstance and return response metadata - # 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'), - } + :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. - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - 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 - :rtype: twilio.rest.chat.v2.credential.CredentialContext + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - if self._context is None: - self._context = CredentialContext(self._version, sid=self._solution['sid'], ) - return self._context + Asynchronous coroutine to update the CredentialInstance - @property - def sid(self): + :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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['sid'] + Asynchronous coroutine to update the CredentialInstance and return response metadata - @property - def account_sid(self): + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Provide a friendly representation + + :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 friendly_name(self): + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Build an instance of CredentialInstance + + :param payload: Payload response from the API """ - return self._properties['friendly_name'] - @property - def type(self): + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: """ - :returns: The type of push-notification service the credential is for - :rtype: CredentialInstance.PushService + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['type'] + return "" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource - @property - def sandbox(self): """ - :returns: [APN only] Whether to send the credential to sandbox APNs - :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, + ) -> tuple: """ - return self._properties['sandbox'] + Internal helper for create operation - @property - def date_created(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['date_created'] + Create the CredentialInstance - @property - def date_updated(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 ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Create the CredentialInstance and return response metadata - @property - def url(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: ApiResponse with instance, status code, and headers """ - :returns: The absolute URL of the Credential resource - :rtype: unicode + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: """ - return self._properties['url'] + Internal async helper for create operation - def fetch(self): + Returns: + tuple: (payload, status_code, headers) """ - Fetch the CredentialInstance - :returns: The fetched CredentialInstance - :rtype: twilio.rest.chat.v2.credential.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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._proxy.fetch() + Asynchronously create the CredentialInstance - 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 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 """ - Update the CredentialInstance + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata - :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 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 - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.update( + payload, status_code, headers = await self._create_async( + type=type, friendly_name=friendly_name, certificate=certificate, private_key=private_key, @@ -433,22 +909,394 @@ def update(self, friendly_name=values.unset, certificate=values.unset, api_key=api_key, secret=secret, ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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. - def delete(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 """ - Deletes the CredentialInstance + limits = self._version.read_limits(limit, page_size) + page = self.page(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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: """ - return self._proxy.delete() + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The SID of the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The SID of the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 a21423f9f2..de0bab251a 100644 --- a/twilio/rest/chat/v2/service/__init__.py +++ b/twilio/rest/chat/v2/service/__init__.py @@ -1,17 +1,25 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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 +27,2027 @@ from twilio.rest.chat.v2.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/iam/api/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :ivar default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :ivar default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :ivar read_status_enabled: Whether the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature is enabled. The default is `true`. + :ivar reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) is enabled for this Service instance. The default is `false`. + :ivar typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :ivar consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :ivar limits: An object that describes the limits of the service instance. The `limits` object contains `channel_members` to describe the members/channel limit and `user_channels` to describe the channels/user limit. `channel_members` can be 1,000 or less, with a default of 250. `user_channels` can be 1,000 or less, with a default value of 100. + :ivar pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :ivar post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :ivar notifications: The notification configuration for the Service instance. See [Push Notification Configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :ivar media: An object that describes the properties of media that the service supports. The object contains the `size_limit_mb` property, which describes the size of the largest media file in MB; and the `compatibility_message` property, which contains the message text to send when a media message does not have any text. + :ivar url: The absolute URL of the Service resource. + :ivar links: The absolute URLs of the Service's [Channels](https://www.twilio.com/docs/chat/channels), [Roles](https://www.twilio.com/docs/chat/rest/role-resource), [Bindings](https://www.twilio.com/docs/chat/rest/binding-resource), and [Users](https://www.twilio.com/docs/chat/rest/user-resource). + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.default_service_role_sid: Optional[str] = payload.get( + "default_service_role_sid" + ) + self.default_channel_role_sid: Optional[str] = payload.get( + "default_channel_role_sid" + ) + self.default_channel_creator_role_sid: Optional[str] = payload.get( + "default_channel_creator_role_sid" + ) + self.read_status_enabled: Optional[bool] = payload.get("read_status_enabled") + self.reachability_enabled: Optional[bool] = payload.get("reachability_enabled") + self.typing_indicator_timeout: Optional[int] = deserialize.integer( + payload.get("typing_indicator_timeout") + ) + self.consumption_report_interval: Optional[int] = deserialize.integer( + payload.get("consumption_report_interval") + ) + self.limits: Optional[Dict[str, object]] = payload.get("limits") + self.pre_webhook_url: Optional[str] = payload.get("pre_webhook_url") + self.post_webhook_url: Optional[str] = payload.get("post_webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.webhook_filters: Optional[List[str]] = payload.get("webhook_filters") + self.pre_webhook_retry_count: Optional[int] = deserialize.integer( + payload.get("pre_webhook_retry_count") + ) + self.post_webhook_retry_count: Optional[int] = deserialize.integer( + payload.get("post_webhook_retry_count") + ) + self.notifications: Optional[Dict[str, object]] = payload.get("notifications") + self.media: Optional[Dict[str, object]] = payload.get("media") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[ServiceContext] = None - 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 + + :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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) - :param Version version: Version that contains the resource + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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.ServiceList - :rtype: twilio.rest.chat.v2.service.ServiceList + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + return self._proxy.bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation """ - super(ServiceList, self).__init__(version) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The SID of the Service resource to update. + """ + super().__init__(version) # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) - def create(self, friendly_name): + self._bindings: Optional[BindingList] = None + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def _delete(self) -> tuple: """ - Create the ServiceInstance + Internal helper for delete operation - :param unicode friendly_name: A string to describe the resource + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: The created ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. + + :returns: The updated ServiceInstance + """ + payload, _, _ = self._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 ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + if self._bindings is None: + self._bindings = BindingList( + self._version, + self._solution["sid"], + ) + return self._bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) + return self._channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + if self._roles is None: + self._roles = RoleList( + self._version, + self._solution["sid"], + ) + return self._roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation """ - data = values.of({'FriendlyName': friendly_name, }) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return ServiceInstance(self._version, payload, ) +class ServicePage(Page): - def stream(self, limit=None, page_size=None): + def get_instance(self, payload: Dict[str, Any]) -> 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Build an instance of ServiceInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.ServiceInstance] + :param payload: Payload response from the API """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits['page_size'], ) + return ServiceInstance(self._version, payload) - return self._version.stream(page, limits['limit'], limits['page_limit']) + def __repr__(self) -> str: + """ + Provide a friendly representation - def list(self, limit=None, page_size=None): + :returns: Machine friendly representation """ - Lists ServiceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return "" - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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] - """ - return list(self.stream(limit=limit, page_size=page_size, )) +class ServiceList(ListResource): - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def __init__(self, version: Version): """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately + Initialize the ServiceList - :param str page_token: PageToken provided by the API - :param 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 - :returns: Page of ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServicePage """ - 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, ) + self._uri = "/Services" - return ServicePage(self._version, response, self._solution) - - def get_page(self, target_url): + def _create(self, friendly_name: str) -> tuple: """ - 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 + Internal helper for create operation - :returns: Page of ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServicePage + Returns: + tuple: (payload, status_code, headers) """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + + data = values.of( + { + "FriendlyName": friendly_name, + } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - return ServicePage(self._version, response, self._solution) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def get(self, sid): + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, friendly_name: str) -> ServiceInstance: """ - Constructs a ServiceContext + Create the ServiceInstance - :param sid: The SID of the Service resource to fetch + :param friendly_name: A descriptive string that you create to describe the new resource. - :returns: twilio.rest.chat.v2.service.ServiceContext - :rtype: twilio.rest.chat.v2.service.ServiceContext + :returns: The created ServiceInstance """ - return ServiceContext(self._version, sid=sid, ) + payload, _, _ = self._create(friendly_name=friendly_name) + return ServiceInstance(self._version, payload) - def __call__(self, sid): + def create_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Constructs a ServiceContext + Create the ServiceInstance and return response metadata - :param sid: The SID of the Service resource to fetch + :param friendly_name: A descriptive string that you create to describe the new resource. - :returns: twilio.rest.chat.v2.service.ServiceContext - :rtype: twilio.rest.chat.v2.service.ServiceContext + :returns: ApiResponse with instance, status code, and headers """ - return ServiceContext(self._version, sid=sid, ) + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _create_async(self, friendly_name: str) -> tuple: """ - Provide a friendly representation + Internal async helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class ServicePage(Page): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, response, solution): - """ - Initialize the ServicePage + headers["Accept"] = "application/json" - :param Version version: Version that contains the resource - :param Response response: Response from the API + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.chat.v2.service.ServicePage - :rtype: twilio.rest.chat.v2.service.ServicePage + async def create_async(self, friendly_name: str) -> ServiceInstance: """ - super(ServicePage, self).__init__(version, response) + Asynchronously create the ServiceInstance - # Path Solution - self._solution = solution + :param friendly_name: A descriptive string that you create to describe the new resource. - def get_instance(self, payload): + :returns: The created ServiceInstance """ - Build an instance of ServiceInstance + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return ServiceInstance(self._version, payload) - :param dict payload: Payload response from the API - - :returns: twilio.rest.chat.v2.service.ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: """ - return ServiceInstance(self._version, payload, ) + Asynchronously create the ServiceInstance and return response metadata - def __repr__(self): - """ - Provide a friendly representation + :param friendly_name: A descriptive string that you create to describe the new resource. - :returns: Machine friendly representation - :rtype: str + :returns: ApiResponse with instance, status code, and headers """ - return '' + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + 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. -class ServiceContext(InstanceContext): - """ """ + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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, sid): + :returns: Generator that will yield up to limit results """ - Initialize the ServiceContext + 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 sid: The SID of the Service resource to fetch + return self._version.stream(page, limits["limit"]) - :returns: twilio.rest.chat.v2.service.ServiceContext - :rtype: twilio.rest.chat.v2.service.ServiceContext + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: """ - super(ServiceContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) + 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. - # Dependents - self._channels = None - self._roles = None - self._users = None - self._bindings = None + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def fetch(self): + :returns: Generator that will yield up to limit results """ - Fetch the ServiceInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :returns: The fetched ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Streams ServiceInstance and returns headers from first page - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - def delete(self): - """ - Deletes the 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: 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): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - 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 + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - :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'], ) + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - @property - def channels(self): + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Access the channels + Asynchronously streams ServiceInstance and returns headers from first page - :returns: twilio.rest.chat.v2.service.channel.ChannelList - :rtype: twilio.rest.chat.v2.service.channel.ChannelList - """ - if self._channels is None: - self._channels = ChannelList(self._version, service_sid=self._solution['sid'], ) - return self._channels - @property - def roles(self): - """ - Access the roles + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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.role.RoleList - :rtype: twilio.rest.chat.v2.service.role.RoleList + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - if self._roles is None: - self._roles = RoleList(self._version, service_sid=self._solution['sid'], ) - return self._roles + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def users(self): - """ - Access the users + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: twilio.rest.chat.v2.service.user.UserList - :rtype: twilio.rest.chat.v2.service.user.UserList + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: """ - if self._users is None: - self._users = UserList(self._version, service_sid=self._solution['sid'], ) - return self._users + 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 bindings(self): - """ - Access the bindings + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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.v2.service.binding.BindingList - :rtype: twilio.rest.chat.v2.service.binding.BindingList + :returns: list that will contain up to limit results """ - if self._bindings is None: - self._bindings = BindingList(self._version, service_sid=self._solution['sid'], ) - return self._bindings - def __repr__(self): - """ - 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[ServiceInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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) -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'), - } + :returns: list that will contain up to limit results + """ - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def _proxy(self): + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists ServiceInstance and returns headers from first page - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.chat.v2.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 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 account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['account_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def friendly_name(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] + Asynchronously lists ServiceInstance and returns headers from first page - @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'] + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 default_service_role_sid(self): + :returns: ApiResponse with list of instances, status code, and headers """ - :returns: The service role assigned to users when they are added to the service - :rtype: unicode - """ - return self._properties['default_service_role_sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def default_channel_role_sid(self): - """ - :returns: The channel role assigned to users when they are added to a channel - :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, + ) -> ServicePage: """ - return self._properties['default_channel_role_sid'] + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - @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'] + :param page_token: PageToken provided by the 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 read_status_enabled(self): - """ - :returns: Whether the Message Consumption Horizon feature is enabled - :rtype: bool + :returns: Page of ServiceInstance """ - return self._properties['read_status_enabled'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def reachability_enabled(self): - """ - :returns: Whether the Reachability Indicator feature is enabled for this Service instance - :rtype: bool - """ - return self._properties['reachability_enabled'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def typing_indicator_timeout(self): - """ - :returns: How long in seconds to wait before assuming the user is no longer typing - :rtype: unicode - """ - return self._properties['typing_indicator_timeout'] + headers["Accept"] = "application/json" - @property - def consumption_report_interval(self): - """ - :returns: DEPRECATED - :rtype: unicode - """ - return self._properties['consumption_report_interval'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) - @property - def limits(self): + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: """ - :returns: An object that describes the limits of the service instance - :rtype: dict - """ - return self._properties['limits'] + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - @property - def pre_webhook_url(self): - """ - :returns: The webhook URL for pre-event webhooks - :rtype: unicode - """ - return self._properties['pre_webhook_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 post_webhook_url(self): - """ - :returns: The URL for post-event webhooks - :rtype: unicode + :returns: Page of ServiceInstance """ - return self._properties['post_webhook_url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def webhook_method(self): - """ - :returns: The HTTP method to use for both PRE and POST webhooks - :rtype: unicode - """ - return self._properties['webhook_method'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def webhook_filters(self): - """ - :returns: The list of webhook events that are enabled for this Service instance - :rtype: unicode - """ - return self._properties['webhook_filters'] + headers["Accept"] = "application/json" - @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'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) - @property - def post_webhook_retry_count(self): + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The number of times calls to the `post_webhook_url` will be retried - :rtype: unicode - """ - return self._properties['post_webhook_retry_count'] + Retrieve a single page with response metadata - @property - def notifications(self): - """ - :returns: The notification configuration for the Service instance - :rtype: dict - """ - return self._properties['notifications'] - @property - def media(self): - """ - :returns: The properties of the media that the service supports - :rtype: dict - """ - return self._properties['media'] + :param page_token: PageToken provided by the 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: ApiResponse with ServicePage, status code, and headers """ - :returns: The absolute URL of the Service resource - :rtype: unicode - """ - return self._properties['url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def links(self): - """ - :returns: The absolute URLs of the Service's Channels, Roles, and Users - :rtype: unicode - """ - return self._properties['links'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def fetch(self): - """ - Fetch the ServiceInstance + headers["Accept"] = "application/json" - :returns: The fetched ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance - """ - return self._proxy.fetch() + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - def delete(self): + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the ServiceInstance + Asynchronously retrieve a single page with response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - 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): + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers """ - Update the ServiceInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :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 + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: The updated ServiceInstance - :rtype: twilio.rest.chat.v2.service.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, + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def channels(self): + 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 f49ea87cb5..cd5b0d1dc0 100644 --- a/twilio/rest/chat/v2/service/binding.py +++ b/twilio/rest/chat/v2/service/binding.py @@ -1,438 +1,873 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +class BindingInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the BindingList + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the Binding 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/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") - :returns: twilio.rest.chat.v2.service.binding.BindingList - :rtype: twilio.rest.chat.v2.service.binding.BindingList - """ - super(BindingList, self).__init__(version) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Bindings'.format(**self._solution) + 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'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, binding_type=values.unset, identity=values.unset, limit=None, - page_size=None): + async def delete_async(self) -> bool: """ - Lists BindingInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the BindingInstance - :param BindingInstance.BindingType binding_type: The 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 delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of BindingInstance records from the API. - Request is executed immediately + Deletes the BindingInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - 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, - }) + return self._proxy.delete_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance with HTTP info - return BindingPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with success boolean, status code, and headers """ - Retrieve a specific page of BindingInstance records from the API. - Request is executed immediately + return await self._proxy.delete_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def fetch(self) -> "BindingInstance": + """ + Fetch the BindingInstance - :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 self._proxy.fetch() + + async def fetch_async(self) -> "BindingInstance": + """ + Asynchronous coroutine to fetch the BindingInstance - return BindingPage(self._version, response, self._solution) - def get(self, sid): + :returns: The fetched BindingInstance """ - Constructs a BindingContext + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return BindingContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.fetch_with_http_info() - def __call__(self, sid): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Constructs a BindingContext + Asynchronous coroutine to fetch the BindingInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return BindingContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.fetch_with_http_info_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 BindingPage(Page): - """ """ +class BindingContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the BindingPage - - :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 + Initialize the BindingContext - :returns: twilio.rest.chat.v2.service.binding.BindingPage - :rtype: twilio.rest.chat.v2.service.binding.BindingPage + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the Binding resource from. + :param sid: The SID of the Binding resource to fetch. """ - super(BindingPage, 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}/Bindings/{sid}".format(**self._solution) - def get_instance(self, payload): + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of BindingInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.chat.v2.service.binding.BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return BindingInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the BindingInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the BindingInstance and return response metadata -class BindingContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the BindingContext - :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 + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v2.service.binding.BindingContext - :rtype: twilio.rest.chat.v2.service.binding.BindingContext + async def delete_async(self) -> bool: """ - super(BindingContext, self).__init__(version) + Asynchronous coroutine that deletes the BindingInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Bindings/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BindingInstance: """ Fetch the BindingInstance + :returns: The fetched BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the BindingInstance + Asynchronous coroutine to fetch the BindingInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 BindingInstance(InstanceResource): - """ """ +class BindingPage(Page): - class BindingType(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: + """ + Build an instance of BindingInstance - 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'), - } + :param payload: Payload response from the API + """ - # 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 __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: BindingContext for this BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingContext + :returns: Machine friendly representation """ - if self._context is None: - self._context = BindingContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return "" - @property - def sid(self): + +class BindingList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - :returns: The unique string that identifies the resource - :rtype: unicode + Initialize the BindingList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Binding resources from. + """ - return self._properties['sid'] + super().__init__(version) - @property - def account_sid(self): + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Bindings".format(**self._solution) + + def stream( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BindingInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['account_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 service_sid(self): + 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]: """ - :returns: The SID of the Service that the Binding resource is associated with - :rtype: unicode + Asynchronously streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['service_sid'] + 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 date_created(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Streams BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) - @property - def date_updated(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Asynchronously streams BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) - @property - def endpoint(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 unique endpoint identifier 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 self._properties['endpoint'] - @property - def identity(self): + 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]: """ - :returns: The string that identifies the resource's User - :rtype: unicode + Asynchronously lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['identity'] + Lists BindingInstance and returns headers from first page - @property - def credential_sid(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: ApiResponse with list of instances, status code, and headers """ - :returns: The SID of the Credential for the binding - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['credential_sid'] + Asynchronously lists BindingInstance and returns headers from first page - @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: ApiResponse with list of instances, status code, and headers """ - :returns: The push technology to use for the binding - :rtype: BindingInstance.BindingType + generator, status_code, headers = await self.stream_with_http_info_async( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['binding_type'] + Retrieve a single page of BindingInstance records from the API. + Request is executed immediately - @property - def message_types(self): + :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 """ - :returns: The Programmable Chat message types the binding is subscribed to - :rtype: unicode + 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, solution=self._solution) + + async def page_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Asynchronously retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance """ - 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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with BindingPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with BindingPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 358abc09b5..d2c4bf396c 100644 --- a/twilio/rest/chat/v2/service/channel/__init__.py +++ b/twilio/rest/chat/v2/service/channel/__init__.py @@ -1,17 +1,25 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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 +27,1651 @@ 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, + } - 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): - """ - Create the ChannelInstance + self._context: Optional[ChannelContext] = None - :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 + @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: 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, }) + 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, headers=headers, ) + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ChannelInstance - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - 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( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.ChannelInstance] + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> 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'], ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def list(self, type=values.unset, limit=None, page_size=None): + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - Lists ChannelInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the ChannelInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(type=type, limit=limit, page_size=page_size, )) + return self._proxy.delete_with_http_info( + 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): + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - Retrieve a single page of ChannelInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the ChannelInstance with HTTP info - :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 + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: Page of ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelPage + :returns: ApiResponse with success boolean, status code, and headers """ - 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 ChannelPage(self._version, response, self._solution) + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def get_page(self, target_url): + def fetch(self) -> "ChannelInstance": """ - Retrieve a specific page of ChannelInstance records from the API. - Request is executed immediately + Fetch the ChannelInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelPage + :returns: The fetched ChannelInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ChannelPage(self._version, response, self._solution) + return self._proxy.fetch() - def get(self, sid): + async def fetch_async(self) -> "ChannelInstance": """ - Constructs a ChannelContext + Asynchronous coroutine to fetch the ChannelInstance - :param sid: The SID of the resource - :returns: twilio.rest.chat.v2.service.channel.ChannelContext - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + :returns: The fetched ChannelInstance """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.fetch_async() - def __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a ChannelContext + Fetch the ChannelInstance with HTTP info - :param sid: The SID of the resource - :returns: twilio.rest.chat.v2.service.channel.ChannelContext - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + :returns: ApiResponse with instance, status code, and headers """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.fetch_with_http_info() - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the ChannelInstance with HTTP info - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - return '' + return await self._proxy.fetch_with_http_info_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 -class ChannelPage(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`. - def __init__(self, version, response, solution): + :returns: The updated ChannelInstance """ - Initialize the ChannelPage + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) - :param 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 + 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: twilio.rest.chat.v2.service.channel.ChannelPage - :rtype: twilio.rest.chat.v2.service.channel.ChannelPage + :returns: The updated ChannelInstance """ - super(ChannelPage, self).__init__(version, response) + 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, + ) - # Path Solution - self._solution = solution + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ChannelInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) - def get_instance(self, payload): + @property + def invites(self) -> InviteList: """ - Build an instance of ChannelInstance + Access the invites + """ + return self._proxy.invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + return self._proxy.members - :param dict payload: Payload response from the API + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages - :returns: twilio.rest.chat.v2.service.channel.ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks """ - return ChannelInstance(self._version, payload, service_sid=self._solution['service_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 ChannelContext(InstanceContext): - """ """ - def __init__(self, version, service_sid, sid): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the ChannelContext - :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 - - :returns: twilio.rest.chat.v2.service.channel.ChannelContext - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the Channel resource in. + :param sid: The SID of the Channel resource to update. This value can be either the `sid` or the `unique_name` of the Channel resource to update. """ - super(ChannelContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Channels/{sid}'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) - # Dependents - self._members = None - self._messages = None - self._invites = None - self._webhooks = None + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None + self._webhooks: Optional[WebhookList] = None - def fetch(self): + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: """ - Fetch the ChannelInstance + Internal helper for delete operation - :returns: The fetched ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) - return ChannelInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers ) - def delete(self, x_twilio_webhook_enabled=values.unset): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ Deletes the ChannelInstance - :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 :returns: True if delete succeeds, False otherwise - :rtype: bool """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success - 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 delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - Update the ChannelInstance + Deletes the ChannelInstance and return response metadata - :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 - :returns: The updated ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + :returns: ApiResponse with success boolean, status code, and 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({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - - 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'], + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return ApiResponse(data=success, status_code=status_code, headers=headers) - @property - def members(self): + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: """ - Access the members + Internal async helper for delete operation - :returns: twilio.rest.chat.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + Returns: + tuple: (success_boolean, status_code, headers) """ - if self._members is None: - self._members = MemberList( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], - ) - return self._members + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) - @property - def messages(self): - """ - Access the messages + headers = values.of({}) - :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'], - ) - return self._messages + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - @property - def invites(self): + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Access the invites + Asynchronous coroutine that deletes the ChannelInstance - :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 + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - @property - def webhooks(self): + :returns: True if delete succeeds, False otherwise """ - Access the webhooks + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return success - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookList - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookList + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - if self._webhooks is None: - self._webhooks = WebhookList( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], - ) - return self._webhooks + Asynchronous coroutine that deletes the ChannelInstance and return response metadata - def __repr__(self): + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers """ - Provide a friendly representation + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) - :returns: Machine friendly representation - :rtype: str + def _fetch(self) -> tuple: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Internal helper for fetch operation + Returns: + tuple: (payload, status_code, headers) + """ -class ChannelInstance(InstanceResource): - """ """ + headers = values.of({}) - class ChannelType(object): - PUBLIC = "public" - PRIVATE = "private" + headers["Accept"] = "application/json" - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - 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'), - } + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): + :returns: The fetched ChannelInstance """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, _, _ = self._fetch() + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - :returns: ChannelContext for this ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + def fetch_with_http_info(self) -> ApiResponse: """ - if self._context is None: - self._context = ChannelContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Fetch the ChannelInstance and return response metadata - @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 + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['account_sid'] + payload, status_code, headers = self._fetch() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def service_sid(self): + async def _fetch_async(self) -> tuple: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + Internal async helper for fetch operation - @property - def friendly_name(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - @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({}) - @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'] + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - @property - def date_created(self): + async def fetch_async(self) -> ChannelInstance: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + Asynchronous coroutine to fetch 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'] - @property - def created_by(self): - """ - :returns: The identity of the User that created the channel - :rtype: unicode + :returns: The fetched ChannelInstance """ - return self._properties['created_by'] + payload, _, _ = await self._fetch_async() + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - @property - def members_count(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: The number of Members in the Channel - :rtype: unicode - """ - return self._properties['members_count'] + Asynchronous coroutine to fetch the ChannelInstance and return response metadata - @property - def messages_count(self): - """ - :returns: The number of Messages that have been passed in the Channel - :rtype: unicode - """ - return self._properties['messages_count'] - @property - def url(self): - """ - :returns: The absolute URL of the Channel resource - :rtype: unicode + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['url'] + payload, status_code, headers = await self._fetch_async() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The updated ChannelInstance + """ + payload, _, _ = self._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 ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def links(self): + def invites(self) -> InviteList: """ - :returns: Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel - :rtype: unicode + Access the invites """ - return self._properties['links'] + if self._invites is None: + self._invites = InviteList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._invites - def fetch(self): + @property + def members(self) -> MemberList: """ - Fetch the ChannelInstance + Access the members + """ + if self._members is None: + self._members = MemberList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._members - :returns: The fetched ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + @property + def messages(self) -> MessageList: """ - return self._proxy.fetch() + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._messages - def delete(self, x_twilio_webhook_enabled=values.unset): + @property + def webhooks(self) -> WebhookList: """ - Deletes the ChannelInstance + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._webhooks - :param ChannelInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Machine friendly representation """ - return self._proxy.delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - 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): + +class ChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: """ - Update the ChannelInstance + Build an instance of 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 payload: Payload response from the API + """ - :returns: The updated ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: """ - return self._proxy.update( + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ChannelList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Channel resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Channels".format(**self._solution) + + def _create( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the Channel resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used in cases where a Channel is being recreated from a backup/separate source and where a Message was previously updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The created ChannelInstance + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, friendly_name=friendly_name, unique_name=unique_name, attributes=attributes, + type=type, date_created=date_created, date_updated=date_updated, created_by=created_by, + ) + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def members(self): + def stream( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: """ - Access the members + 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: twilio.rest.chat.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + :returns: Generator that will yield up to limit results """ - return self._proxy.members + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) - @property - def messages(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]: """ - Access the messages + 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: twilio.rest.chat.v2.service.channel.message.MessageList - :rtype: twilio.rest.chat.v2.service.channel.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(type=type, page_size=limits["page_size"]) - @property - def invites(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Access the invites + Streams ChannelInstance and returns headers from first page + + + :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: twilio.rest.chat.v2.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteList + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._proxy.invites + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + type=type, page_size=limits["page_size"] + ) - @property - def webhooks(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Access the webhooks + Asynchronously streams ChannelInstance and returns headers from first page + + + :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: twilio.rest.chat.v2.service.channel.webhook.WebhookList - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookList + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._proxy.webhooks + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + type=type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + type=type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Asynchronously lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChannelInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + type=type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChannelInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + type=type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, solution=self._solution) + + async def page_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ChannelPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ChannelPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ChannelPage: + """ + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ChannelPage: + """ + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: The SID of the Channel resource to update. This value can be either the `sid` or the `unique_name` of the Channel resource to update. + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: The SID of the Channel resource to update. This value can be either the `sid` or the `unique_name` of the Channel resource to update. + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 6a29535a48..1a3be5b92a 100644 --- a/twilio/rest/chat/v2/service/channel/invite.py +++ b/twilio/rest/chat/v2/service/channel/invite.py @@ -1,448 +1,985 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 + return self._proxy.delete() - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The Role assigned to the new member + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance - :returns: The created InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + + :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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance with HTTP info - return InviteInstance( - 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: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.invite.InviteInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "InviteInstance": + """ + Fetch the InviteInstance - page = self.page(identity=identity, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched InviteInstance + """ + return self._proxy.fetch() - def list(self, identity=values.unset, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to 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. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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 """ - return list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of InviteInstance records from the API. - Request is executed immediately + Fetch the InviteInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance with HTTP info - return InvitePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of InviteInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InvitePage + :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 InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the InviteContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the Invite resource from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Invite resource to fetch belongs to. This value can be the Channel resource's `sid` or `unique_name`. + :param sid: The SID of the Invite resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Invites/{sid}".format( + **self._solution + ) ) - return InvitePage(self._version, response, self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation - def get(self, sid): + Returns: + tuple: (success_boolean, status_code, headers) """ - Constructs a InviteContext - :param sid: The SID of the Invite resource to fetch + headers = values.of({}) - :returns: twilio.rest.chat.v2.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteContext + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return InviteContext( + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + payload, _, _ = self._fetch() + 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 __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a InviteContext + Fetch the InviteInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return InviteContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class InvitePage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> InviteInstance: """ - Initialize the InvitePage + Asynchronous coroutine to fetch the InviteInstance + - :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 + :returns: The fetched InviteInstance + """ + payload, _, _ = await self._fetch_async() + 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 + async def fetch_with_http_info_async(self) -> ApiResponse: """ - super(InvitePage, self).__init__(version, response) + Asynchronous coroutine to fetch the InviteInstance and return response metadata - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of InviteInstance + payload, status_code, headers = await self._fetch_async() + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.chat.v2.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + :returns: Machine friendly representation """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: + """ + Build an instance of InviteInstance + + :param payload: Payload response from the API + """ + return InviteInstance( self._version, payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + 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 + ) -> tuple: """ - Fetch the InviteInstance + Internal helper for create operation - :returns: The fetched InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the new member. + + :returns: The created InviteInstance + """ + payload, _, _ = self._create(identity=identity, role_sid=role_sid) 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): + def create_with_http_info( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: """ - Deletes the InviteInstance + Create the InviteInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: """ - Provide a friendly representation + Internal async helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - 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"}) -class InviteInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, payload, service_sid, channel_sid, sid=None): + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: """ - Initialize the InviteInstance + Asynchronously create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the new member. - :returns: twilio.rest.chat.v2.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + :returns: The created InviteInstance """ - super(InviteInstance, self).__init__(version) + payload, _, _ = await self._create_async(identity=identity, role_sid=role_sid) + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - # 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'), - } + async def create_with_http_info_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the InviteInstance and return response metadata - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + :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. - @property - def _proxy(self): + :returns: ApiResponse with instance, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, status_code, headers = await self._create_async( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: InviteContext for this InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteContext + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[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 + 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 sid(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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InviteInstance]: """ - return self._properties['sid'] + 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 account_sid(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 """ - :returns: The SID of the Account that created the resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['account_sid'] + Streams InviteInstance and returns headers from first page - @property - def channel_sid(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The SID of the Channel the new resource belongs to - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['channel_sid'] + Asynchronously streams InviteInstance and returns headers from first page - @property - def service_sid(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - return self._properties['service_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. - @property - def identity(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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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 identifies the resource's User - :rtype: unicode + + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - return self._properties['identity'] + 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 date_created(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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_created'] + Lists InviteInstance and returns headers from first page - @property - def date_updated(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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously lists InviteInstance and returns headers from first page - @property - def role_sid(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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - :returns: The SID of the Role assigned to the member - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['role_sid'] + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately - @property - def created_by(self): + :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 """ - :returns: The identity of the User that created the invite - :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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, solution=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: """ - return self._properties['created_by'] + Asynchronously retrieve a single page of InviteInstance records from the API. + Request is executed immediately - @property - def url(self): + :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 """ - :returns: The absolute URL of the Invite 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 InvitePage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['url'] + Retrieve a single page with response metadata + + + :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 - def fetch(self): + :returns: ApiResponse with InvitePage, status code, and headers """ - Fetch the InviteInstance + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: The fetched InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with InvitePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> InvitePage: """ - return self._proxy.fetch() + Retrieve a specific page of InviteInstance 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 InviteInstance """ - Deletes the InviteInstance + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, solution=self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def get_page_async(self, target_url: str) -> InvitePage: """ - return self._proxy.delete() + Asynchronously retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: The SID of the Invite resource to fetch. + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: The SID of the Invite resource to fetch. + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 5679d008ac..9e40454a44 100644 --- a/twilio/rest/chat/v2/service/channel/member.py +++ b/twilio/rest/chat/v2/service/channel/member.py @@ -1,563 +1,1630 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class MemberList(ListResource): - """ """ +class MemberInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the Member resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Member resource. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Member resource belongs to. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Member resource is associated with. + :ivar identity: The application-defined string that uniquely identifies the resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the member. + :ivar last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :ivar last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :ivar url: The absolute URL of the Member resource. + :ivar attributes: The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) + self.url: Optional[str] = payload.get("url") + self.attributes: Optional[str] = payload.get("attributes") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } - def __init__(self, version, service_sid, channel_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 SID 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.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - super(MemberList, self).__init__(version) + Deletes the MemberInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'channel_sid': channel_sid, } - self._uri = '/Services/{service_sid}/Channels/{channel_sid}/Members'.format(**self._solution) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - 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): + :returns: True if delete succeeds, False otherwise """ - Create the MemberInstance + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - :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 + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance - :returns: The created MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - 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, }) + Deletes the MemberInstance with HTTP info - 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: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) - def stream(self, identity=values.unset, limit=None, page_size=None): + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - 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. + Asynchronous coroutine that deletes the MemberInstance with HTTP info - :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) + :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.member.MemberInstance] + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - page = self.page(identity=identity, page_size=limits['page_size'], ) + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, identity=values.unset, limit=None, page_size=None): + :returns: The fetched MemberInstance """ - Lists MemberInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return 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. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.member.MemberInstance] + + :returns: The fetched MemberInstance """ - return list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of MemberInstance records from the API. - Request is executed immediately + Fetch the MemberInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance with HTTP info - return MemberPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of MemberInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance - :returns: Page of MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberPage + :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 """ - 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, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, ) - return MemberPage(self._version, response, self._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. - def get(self, sid): + :returns: The updated MemberInstance """ - Constructs a MemberContext + 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, + ) - :param sid: The SID of the Member resource to fetch + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the MemberInstance with HTTP 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) 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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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, + ) - :returns: twilio.rest.chat.v2.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext - """ - return MemberContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance with HTTP 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) 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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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 __call__(self, sid): + def __repr__(self) -> str: """ - Constructs a MemberContext + Provide a friendly representation - :param sid: The SID of the Member resource to fetch + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MemberContext(InstanceContext): - :returns: twilio.rest.chat.v2.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - return MemberContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + Initialize the MemberContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the Member resource in. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Member resource to update belongs to. This value can be the Channel resource's `sid` or `unique_name`. + :param sid: The SID of the Member resource to update. This value can be either the Member's `sid` or its `identity` value. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Members/{sid}".format( + **self._solution + ) ) - def __repr__(self): + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: """ - Provide a friendly representation + Internal helper for delete operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (success_boolean, status_code, headers) """ - return '' + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + headers = values.of({}) -class MemberPage(Page): - """ """ + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Initialize the MemberPage + Deletes 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 SID of the Channel for the member + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.chat.v2.service.channel.member.MemberPage - :rtype: twilio.rest.chat.v2.service.channel.member.MemberPage + :returns: True if delete succeeds, False otherwise """ - super(MemberPage, self).__init__(version, response) + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success - # Path Solution - self._solution = solution + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MemberInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def get_instance(self, payload): + :returns: ApiResponse with success boolean, status code, and headers """ - Build an instance of MemberInstance + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation - :returns: twilio.rest.chat.v2.service.channel.member.MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - return MemberInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } ) - def __repr__(self): + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the MemberInstance - :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 '' + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return success + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance and return response metadata -class MemberContext(InstanceContext): - """ """ + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def __init__(self, version, service_sid, channel_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the MemberContext + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, 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 member belongs to - :param sid: The SID of the Member resource to fetch + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.chat.v2.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext + Returns: + tuple: (payload, status_code, headers) """ - super(MemberContext, 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}/Members/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: """ Fetch the MemberInstance + :returns: The fetched MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + :returns: The fetched MemberInstance + """ + payload, _, _ = await self._fetch_async() 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"], + sid=self._solution["sid"], ) - def delete(self, x_twilio_webhook_enabled=values.unset): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the MemberInstance + Asynchronous coroutine to fetch the MemberInstance and return response metadata - :param MemberInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: ApiResponse with instance, status code, and headers """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + payload, status_code, headers = await self._fetch_async() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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({}) - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + 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" - 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): + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 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 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 - :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._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, + ) + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the MemberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) 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"], + sid=self._solution["sid"], ) - def __repr__(self): + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide 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 MemberInstance(InstanceResource): - """ """ +class MemberPage(Page): - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: + """ + Build an instance of MemberInstance - 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'), - } + :param payload: Payload response from the API + """ + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - # Context - self._context = None + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MemberList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MemberList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Member resources from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Member resources to read belong to. This value can be the Channel resource's `sid` or `unique_name`. + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "channel_sid": channel_sid, } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + def _create( + self, + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, 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", + } + ) - :returns: MemberContext for this MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - 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 + Create the MemberInstance - @property - def sid(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). 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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = self._create( + identity=identity, + 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, + ) + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the MemberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + 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, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, 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", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronously create the MemberInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. This parameter should only be used when recreating a Member from a backup/separate source. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used when a Member is being recreated from a backup/separate source and where a Member was previously updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The created MemberInstance """ - return self._properties['sid'] + payload, _, _ = await self._create_async( + identity=identity, + 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, + ) + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def account_sid(self): + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the MemberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + 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, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) - @property - def channel_sid(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: """ - :returns: The SID of the Channel for the member - :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 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 """ - return self._properties['channel_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) - @property - def service_sid(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + Streams MemberInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['service_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) - @property - def identity(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The string that identifies the resource's User - :rtype: unicode + Asynchronously streams MemberInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['identity'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) - @property - def date_created(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :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 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 self._properties['date_created'] - @property - def date_updated(self): + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Asynchronously lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['date_updated'] - @property - def role_sid(self): + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Role assigned to the member - :rtype: unicode + Lists MemberInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers """ - return self._properties['role_sid'] + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def last_consumed_message_index(self): + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The index of the last Message that the Member has read within the Channel - :rtype: unicode + Asynchronously lists MemberInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers """ - return self._properties['last_consumed_message_index'] + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def last_consumption_timestamp(self): + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: """ - :returns: The ISO 8601 based timestamp string that represents the datetime of the last Message read event for the Member within the Channel - :rtype: datetime + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance """ - return self._properties['last_consumption_timestamp'] + data = values.of( + { + "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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, solution=self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: """ - :returns: The absolute URL of the Member resource - :rtype: unicode + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance """ - 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): + headers = values.of({"Content-Type": "application/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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: """ - :returns: The JSON string that stores application-specific data - :rtype: unicode + Retrieve a single page with response metadata + + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MemberPage, status code, and headers """ - return self._properties['attributes'] + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MemberPage, status code, and headers + """ + 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"}) - def fetch(self): + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 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, + ) - :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 + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext - :returns: The updated MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + :param sid: The SID of the Member resource to update. This value can be either the Member's `sid` or its `identity` value. """ - return self._proxy.update( - role_sid=role_sid, - last_consumed_message_index=last_consumed_message_index, - last_consumption_timestamp=last_consumption_timestamp, - date_created=date_created, - date_updated=date_updated, - attributes=attributes, - x_twilio_webhook_enabled=x_twilio_webhook_enabled, + 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 13a62309c3..ee6de8ed3d 100644 --- a/twilio/rest/chat/v2/service/channel/message.py +++ b/twilio/rest/chat/v2/service/channel/message.py @@ -1,600 +1,1630 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class MessageList(ListResource): - """ """ +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the Message resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Message resource. + :ivar attributes: The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Message resource is associated with. + :ivar to: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) that the message was sent to. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Message resource belongs to. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :ivar was_edited: Whether the message has been edited since it was created. + :ivar _from: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. The default value is `system`. + :ivar body: The content of the message. + :ivar index: The index of the message within the [Channel](https://www.twilio.com/docs/chat/channels). Indices may skip numbers, but will always be in order of when the message was received. + :ivar type: The Message type. Can be: `text` or `media`. + :ivar media: An object that describes the Message's media, if the message contains media. The object contains these fields: `content_type` with the MIME type of the media, `filename` with the name of the media, `sid` with the SID of the Media resource, and `size` with the media object's file size in bytes. If the Message has no media, this value is `null`. + :ivar url: The absolute URL of the Message resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.service_sid: Optional[str] = payload.get("service_sid") + self.to: Optional[str] = payload.get("to") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.last_updated_by: Optional[str] = payload.get("last_updated_by") + self.was_edited: Optional[bool] = payload.get("was_edited") + self._from: Optional[str] = payload.get("from") + self.body: Optional[str] = payload.get("body") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.type: Optional[str] = payload.get("type") + self.media: Optional[Dict[str, object]] = payload.get("media") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } - def __init__(self, version, service_sid, channel_sid): + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": """ - Initialize the MessageList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel the Message resource belongs to + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v2.service.channel.message.MessageList - :rtype: twilio.rest.chat.v2.service.channel.message.MessageList + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - super(MessageList, self).__init__(version) + Deletes the MessageInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'channel_sid': channel_sid, } - self._uri = '/Services/{service_sid}/Channels/{channel_sid}/Messages'.format(**self._solution) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - 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): + :returns: True if delete succeeds, False otherwise """ - Create the MessageInstance + 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 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 + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: The created MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - 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 with HTTP info - 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: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) - def stream(self, order=values.unset, limit=None, page_size=None): + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - 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 with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - page = self.page(order=order, page_size=limits['page_size'], ) + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, order=values.unset, limit=None, page_size=None): + :returns: The fetched MessageInstance """ - Lists MessageInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return self._proxy.fetch() - :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) + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately + Fetch the MessageInstance with HTTP info - :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: """ - data = values.of({ - 'Order': order, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Asynchronous coroutine to fetch the MessageInstance with HTTP info - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return MessagePage(self._version, response, self._solution) + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() - def get_page(self, target_url): + 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": """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately + Update the MessageInstance - :param str target_url: API-generated URL for the requested results page + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :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 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_, ) - return MessagePage(self._version, response, self._solution) + 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. - def get(self, sid): + :returns: The updated MessageInstance """ - Constructs a MessageContext + 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_, + ) - :param sid: The SID of the Message resource to fetch + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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_, + ) - :returns: twilio.rest.chat.v2.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext - """ - return MessageContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, ) - def __call__(self, sid): + def __repr__(self) -> str: """ - Constructs a MessageContext + Provide a friendly representation - :param sid: The SID of the Message resource to fetch + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +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 __repr__(self): + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: """ - Provide a friendly representation + Internal helper for delete operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (success_boolean, status_code, headers) """ - return '' + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + headers = values.of({}) -class MessagePage(Page): - """ """ + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Initialize the MessagePage + 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 SID of the Channel the Message resource belongs to + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.chat.v2.service.channel.message.MessagePage - :rtype: twilio.rest.chat.v2.service.channel.message.MessagePage + :returns: True if delete succeeds, False otherwise """ - super(MessagePage, self).__init__(version, response) + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success - # Path Solution - self._solution = solution + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def get_instance(self, payload): + :returns: ApiResponse with success boolean, status code, and headers """ - Build an instance of MessageInstance + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation - :returns: twilio.rest.chat.v2.service.channel.message.MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - return MessageInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } ) - def __repr__(self): + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 '' + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return success + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance and return response metadata -class MessageContext(InstanceContext): - """ """ + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def __init__(self, version, service_sid, channel_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the MessageContext + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, 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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.chat.v2.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext + Returns: + tuple: (payload, status_code, headers) """ - 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) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> 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, ) - + payload, _, _ = self._fetch() 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Deletes the MessageInstance + Fetch the MessageInstance and return response metadata - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: ApiResponse with instance, status code, and headers """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + payload, status_code, headers = self._fetch() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - 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): + Returns: + tuple: (payload, status_code, headers) """ - 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 - :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 + headers = values.of({}) - :returns: The updated MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> MessageInstance: """ - data = values.of({ - 'Body': body, - 'Attributes': attributes, - 'DateCreated': serialize.iso8601_datetime(date_created), - 'DateUpdated': serialize.iso8601_datetime(date_updated), - 'LastUpdatedBy': last_updated_by, - 'From': from_, - }) - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + Asynchronous coroutine to fetch the MessageInstance - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + :returns: The fetched MessageInstance + """ + payload, _, _ = await self._fetch_async() 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 __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the MessageInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + payload, status_code, headers = await self._fetch_async() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 -class MessageInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - class OrderType(object): - ASC = "asc" - DESC = "desc" + headers["Accept"] = "application/json" - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - 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'), - } + 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 - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. - @property - def _proxy(self): + :returns: The updated MessageInstance """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, _, _ = self._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_, + ) + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) - :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'], + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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_, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 ) - return self._context + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled - @property - def sid(self): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = await self._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 MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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_, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - 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 + 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: """ - return self._properties['account_sid'] + Build an instance of MessageInstance - @property - def attributes(self): + :param payload: Payload response from the API """ - :returns: The JSON string that stores application-specific data - :rtype: unicode + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: """ - return self._properties['attributes'] + Provide a friendly representation - @property - def service_sid(self): + :returns: Machine friendly representation """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + return "" + + +class MessageList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - return self._properties['service_sid'] + Initialize the MessageList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Message resources from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Message resource to read belongs to. This value can be the Channel resource's `sid` or `unique_name`. - @property - def to(self): """ - :returns: The SID of the Channel that the message was sent to - :rtype: unicode + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) + + def _create( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "From": from_, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "Body": body, + "MediaSid": media_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._properties['to'] + Create the MessageInstance - @property - def channel_sid(self): + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param media_sid: The SID of the [Media](https://www.twilio.com/docs/chat/rest/media) to attach to the new Message. + + :returns: The created MessageInstance """ - :returns: The SID of the Channel the Message resource belongs to - :rtype: unicode + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param media_sid: The SID of the [Media](https://www.twilio.com/docs/chat/rest/media) to attach to the new Message. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "From": from_, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "Body": body, + "MediaSid": media_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param media_sid: The SID of the [Media](https://www.twilio.com/docs/chat/rest/media) to attach to the new Message. + + :returns: The created MessageInstance """ - return self._properties['channel_sid'] + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def date_created(self): + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param media_sid: The SID of the [Media](https://www.twilio.com/docs/chat/rest/media) to attach to the new Message. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 """ - :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(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['date_created'] + 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 date_updated(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 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(order=order, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_updated'] + Streams MessageInstance and returns headers from first page - @property - def last_updated_by(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The Identity of the User who last updated the Message - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['last_updated_by'] + Asynchronously streams MessageInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: Whether the message has been edited since it was created - :rtype: bool + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - return self._properties['was_edited'] + 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 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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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 Identity of the message's author - :rtype: unicode + + 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['from_'] + 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 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 """ - :returns: The content of the message - :rtype: unicode + + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['body'] + Lists MessageInstance and returns headers from first page - @property - def index(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: ApiResponse with list of instances, status code, and headers """ - :returns: The index of the message within the Channel - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + order=order, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['index'] + Asynchronously lists MessageInstance and returns headers from first page - @property - def type(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: ApiResponse with list of instances, status code, and headers """ - :returns: The Message type - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['type'] + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately - @property - def media(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 + """ + 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, solution=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: A Media object that describes the Message's media if attached; otherwise, null - :rtype: dict + 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['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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: """ - :returns: The absolute URL of the Message resource - :rtype: unicode + Retrieve a single page with response metadata + + + :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: ApiResponse with MessagePage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "Order": order, + "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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 efab359d88..f5372f3595 100644 --- a/twilio/rest/chat/v2/service/channel/webhook.py +++ b/twilio/rest/chat/v2/service/channel/webhook.py @@ -1,524 +1,1417 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance with HTTP info - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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.webhook.WebhookInstance] + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "WebhookInstance": """ - Retrieve a single page of WebhookInstance records from the API. - Request is executed immediately + 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.chat.v2.service.channel.webhook.WebhookPage + :returns: The fetched WebhookInstance """ - 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) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance - return WebhookPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched WebhookInstance """ - Retrieve a specific page of WebhookInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookPage + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info - return WebhookPage(self._version, response, self._solution) - 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: ApiResponse with instance, status code, and headers """ - Create the WebhookInstance + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance - :param 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 + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. - :returns: The created WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + :returns: The updated WebhookInstance """ - data = values.of({ - 'Type': type, - 'Configuration.Url': configuration_url, - 'Configuration.Method': configuration_method, - 'Configuration.Filters': serialize.map(configuration_filters, lambda e: e), - 'Configuration.Triggers': serialize.map(configuration_triggers, lambda e: e), - 'Configuration.FlowSid': configuration_flow_sid, - 'Configuration.RetryCount': configuration_retry_count, - }) + 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, + ) - payload = self._version.create(method='POST', uri=self._uri, data=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 WebhookInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + :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(self, sid): + def update_with_http_info( + 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, + ) -> ApiResponse: """ - Constructs a WebhookContext + Update the WebhookInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WebhookContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + return self._proxy.update_with_http_info( + 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 __call__(self, sid): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Constructs a WebhookContext + Asynchronous coroutine to update the WebhookInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WebhookContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + return await self._proxy.update_with_http_info_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, ) - def __repr__(self): + 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): - """ """ +class WebhookContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - Initialize the WebhookPage - - :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 + Initialize the WebhookContext - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookPage - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookPage + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) with the Channel that has the Webhook resource to update. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Channel Webhook resource to update belongs to. This value can be the Channel resource's `sid` or `unique_name`. + :param sid: The SID of the Channel Webhook resource to update. """ - super(WebhookPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Webhooks/{sid}".format( + **self._solution + ) + ) - def get_instance(self, payload): + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of WebhookInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return WebhookInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + 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 '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance and return response metadata -class WebhookContext(InstanceContext): - """ """ - def __init__(self, version, service_sid, channel_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the WebhookContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookContext - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookContext + Returns: + tuple: (payload, status_code, headers) """ - super(WebhookContext, 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}/Webhooks/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: """ Fetch the WebhookInstance + :returns: The fetched WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() 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"], + 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, - configuration_retry_count=values.unset): + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: """ Update the WebhookInstance - :param 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 + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. :returns: The updated WebhookInstance - :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, - }) + payload, _, _ = self._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 WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the WebhookInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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({}) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The updated WebhookInstance + """ + payload, _, _ = await self._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, + ) 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"], + sid=self._solution["sid"], ) - def delete(self): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Deletes the WebhookInstance + Asynchronous coroutine to update the WebhookInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._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, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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): - """ """ +class WebhookPage(Page): - class Type(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 + """ - def __init__(self, version, payload, service_sid, channel_sid, sid=None): + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: """ - Initialize the WebhookInstance + Provide a friendly representation - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.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'), - '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')), - } - # Context - self._context = None +class WebhookList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) with the Channel to read the resources from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Channel Webhook resources to read belong to. This value can be the Channel resource's `sid` or `unique_name`. + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "channel_sid": channel_sid, } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Webhooks".format( + **self._solution + ) - @property - def _proxy(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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - 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 WebhookInstance - :returns: WebhookContext for this WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookContext + :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 """ - 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 + payload, _, _ = self._create( + type=type, + 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 WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def sid(self): + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the WebhookInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + 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, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = await self._create_async( + type=type, + 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 WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the WebhookInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + 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, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebhookInstance]: """ - return self._properties['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 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[WebhookInstance]: """ - return self._properties['account_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 service_sid(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Service that the Channel Webhook resource is associated with - :rtype: unicode + Streams WebhookInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['service_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def channel_sid(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Channel the Channel Webhook resource belongs to - :rtype: unicode + Asynchronously streams WebhookInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['channel_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def type(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: """ - :returns: The type of 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['type'] - @property - def url(self): + return 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]: """ - :returns: The absolute URL of the Channel Webhook resource - :rtype: unicode + 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['url'] - @property - def configuration(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The JSON string that describes the configuration object for the channel webhook - :rtype: dict + Lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['configuration'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def date_created(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Asynchronously lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_created'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> WebhookPage: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :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_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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, solution=self._solution) + + async def 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: """ - Fetch the WebhookInstance + Asynchronously retrieve a single page of WebhookInstance records from the API. + Request is executed immediately - :returns: The fetched WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + :param page_token: PageToken provided by the API + :param page_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._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 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): + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Update the WebhookInstance + Retrieve a single page with response metadata - :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 - :returns: The updated WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers """ - 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, + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - def delete(self): + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the WebhookInstance + Asynchronously retrieve a single page with response metadata - :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: ApiResponse with WebhookPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: The SID of the Channel Webhook resource to update. + """ + return WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: The SID of the Channel Webhook resource to update. + """ + return WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 4706e6bb5f..3c6fff8f9c 100644 --- a/twilio/rest/chat/v2/service/role.py +++ b/twilio/rest/chat/v2/service/role.py @@ -1,442 +1,1086 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class RoleList(ListResource): - """ """ +class RoleInstance(InstanceResource): + + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" + + """ + :ivar sid: The unique string that we created to identify the Role resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Role resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Role resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar permissions: An array of the permissions the role has been granted. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Role resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } - def __init__(self, version, service_sid): + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": """ - Initialize the RoleList + 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: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v2.service.role.RoleList - :rtype: twilio.rest.chat.v2.service.role.RoleList + def delete(self) -> bool: """ - super(RoleList, self).__init__(version) + Deletes the RoleInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Roles'.format(**self._solution) - def create(self, friendly_name, type, permission): + :returns: True if delete succeeds, False otherwise """ - Create the RoleInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance - :returns: The created RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Type': type, - 'Permission': serialize.map(permission, lambda e: e), - }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.role.RoleInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.role.RoleInstance] + + :returns: The fetched RoleInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of RoleInstance records from the API. - Request is executed immediately + Fetch the RoleInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info - return RolePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of RoleInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance - :param str target_url: API-generated URL for the requested results page + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RolePage + :returns: The updated RoleInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + permission=permission, ) - return RolePage(self._version, response, self._solution) + 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`. - def get(self, sid): + :returns: The updated RoleInstance """ - Constructs a RoleContext + return await self._proxy.update_async( + permission=permission, + ) - :param sid: The SID of the Role resource to fetch + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + permission=permission, + ) - def __call__(self, sid): + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: """ - Constructs a RoleContext + Asynchronous coroutine to update the RoleInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_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) -> tuple: """ - Build an instance of RoleInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v2.service.role.RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + def delete(self) -> bool: """ - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the RoleInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the RoleInstance and return response metadata -class RoleContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the RoleContext + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :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 + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v2.service.role.RoleContext - :rtype: twilio.rest.chat.v2.service.role.RoleContext + async def delete_async(self) -> bool: """ - super(RoleContext, self).__init__(version) + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance and return response metadata - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Roles/{sid}'.format(**self._solution) - def fetch(self): + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: """ Fetch the RoleInstance + :returns: The fetched RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + :returns: The fetched RoleInstance + """ + payload, _, _ = await self._fetch_async() return RoleInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the RoleInstance + Asynchronous coroutine to fetch the RoleInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, permission: List[str]) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for update operation - def update(self, permission): + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, permission: List[str]) -> RoleInstance: """ 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._update(permission=permission) + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, permission: List[str]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Accept"] = "application/json" + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(permission=permission) 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"], + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 - :returns: twilio.rest.chat.v2.service.role.RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + 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 "" + + +class RoleList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the RoleList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Role resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/Roles".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - 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 - :rtype: twilio.rest.chat.v2.service.role.RoleContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: """ - if self._context is None: - self._context = RoleContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the RoleInstance - @property - def 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 unique string that identifies the resource - :rtype: unicode + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: """ - return self._properties['sid'] + Create the RoleInstance and return response metadata - @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: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Account that created the resource - :rtype: unicode + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for create operation - @property - def service_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: """ - return self._properties['service_sid'] + Asynchronously create the RoleInstance - @property - def friendly_name(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 string that you assigned to describe the resource - :rtype: unicode + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: """ - return self._properties['friendly_name'] + Asynchronously create the RoleInstance and return response metadata - @property - def type(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: ApiResponse with instance, status code, and headers """ - :returns: The type of role - :rtype: RoleInstance.RoleType + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: """ - return self._properties['type'] + 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 permissions(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 array of the permissions the role has been granted - :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['permissions'] + 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_created'] + Streams RoleInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :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_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_updated'] + Asynchronously streams RoleInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The absolute URL of the Role resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: """ - return self._properties['url'] + 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) - def fetch(self): + :returns: list that will contain up to limit results """ - Fetch the RoleInstance - :returns: The fetched RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + return 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._proxy.fetch() + 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) - def delete(self): + :returns: list that will contain up to limit results """ - Deletes the RoleInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.delete() + Lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - def update(self, permission): + :returns: ApiResponse with list of instances, status code, and headers """ - Update the RoleInstance + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoleInstance and returns headers from first page - :param unicode permission: A permission the role should have - :returns: The updated RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.update(permission, ) + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The SID of the Role resource to update. + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The SID of the Role resource to update. + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 112481dfad..b31d666b71 100644 --- a/twilio/rest/chat/v2/service/user/__init__.py +++ b/twilio/rest/chat/v2/service/user/__init__.py @@ -1,563 +1,1379 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page from twilio.rest.chat.v2.service.user.user_binding import UserBindingList from twilio.rest.chat.v2.service.user.user_channel import UserChannelList -class UserList(ListResource): - """ """ +class UserInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the User resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the User resource is associated with. + :ivar attributes: The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the user. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). This value is often a username or an email address, and is case-sensitive. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :ivar is_online: Whether the User is actively connected to the Service instance and online. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, if the User has never been online for the Service instance, even if the Service's `reachability_enabled` is `true`. + :ivar is_notifiable: Whether the User has a potentially valid Push Notification registration (APN or GCM) for the Service instance. If at least one registration exists, `true`; otherwise `false`. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, and if the User has never had a notification registration, even if the Service's `reachability_enabled` is `true`. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar joined_channels_count: The number of Channels the User is a Member of. + :ivar links: The absolute URLs of the [Channel](https://www.twilio.com/docs/chat/channels) and [Binding](https://www.twilio.com/docs/chat/rest/binding-resource) resources related to the user. + :ivar url: The absolute URL of the User resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.role_sid: Optional[str] = payload.get("role_sid") + self.identity: Optional[str] = payload.get("identity") + self.is_online: Optional[bool] = payload.get("is_online") + self.is_notifiable: Optional[bool] = payload.get("is_notifiable") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.joined_channels_count: Optional[int] = deserialize.integer( + payload.get("joined_channels_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[UserContext] = None - def __init__(self, version, service_sid): + @property + def _proxy(self) -> "UserContext": """ - Initialize the UserList + 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: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v2.service.user.UserList - :rtype: twilio.rest.chat.v2.service.user.UserList + def delete(self) -> bool: """ - super(UserList, self).__init__(version) + Deletes the UserInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Users'.format(**self._solution) - def create(self, identity, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset, x_twilio_webhook_enabled=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the UserInstance + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes 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 - :returns: The created UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'Identity': identity, - 'RoleSid': role_sid, - 'Attributes': attributes, - 'FriendlyName': friendly_name, - }) - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.UserInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance - :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 await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of UserInstance records from the API. - Request is executed immediately + Fetch the UserInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info - return UserPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of UserInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance - :param str target_url: API-generated URL for the requested results page + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. - :returns: Page of UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserPage + :returns: The updated UserInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, ) - return UserPage(self._version, response, self._solution) + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. - def get(self, sid): + :returns: The updated UserInstance """ - Constructs a UserContext + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) - :param sid: The SID of the User resource to fetch + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP 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 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: ApiResponse with instance, status code, and headers """ - return UserContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Constructs a UserContext + Asynchronous coroutine to update the UserInstance with HTTP 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 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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) - :param sid: The SID of the User resource to fetch + @property + def user_bindings(self) -> UserBindingList: + """ + 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 + 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_bindings: Optional[UserBindingList] = None + self._user_channels: Optional[UserChannelList] = None + + def _delete(self) -> tuple: """ - Build an instance of UserInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :returns: twilio.rest.chat.v2.service.user.UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the UserInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the UserInstance and return response metadata -class UserContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the UserContext - :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 + headers = values.of({}) - :returns: twilio.rest.chat.v2.service.user.UserContext - :rtype: twilio.rest.chat.v2.service.user.UserContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(UserContext, self).__init__(version) + Asynchronous coroutine that deletes the UserInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Users/{sid}'.format(**self._solution) - # Dependents - self._user_channels = None - self._user_bindings = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", 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, ) + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() 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_with_http_info_async(self) -> ApiResponse: """ - Deletes the UserInstance + Asynchronous coroutine to fetch the UserInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, 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 - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset, x_twilio_webhook_enabled=values.unset): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + :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 + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) 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_with_http_info_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, + ) -> ApiResponse: """ - Access the user_channels + Asynchronous coroutine to update the UserInstance and return response metadata - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelList + :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: ApiResponse with instance, status code, and headers """ - if self._user_channels is None: - self._user_channels = UserChannelList( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['sid'], - ) - return self._user_channels + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 UserPage(Page): - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance - 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'), - } + :param payload: Payload response from the API + """ - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + return UserInstance( + 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: UserContext for this UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserContext + :returns: Machine friendly representation """ - if self._context is None: - self._context = UserContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return "" - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + +class UserList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - return self._properties['sid'] + Initialize the UserList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the User resources from. - @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}/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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['account_sid'] + Create the UserInstance - @property - def service_sid(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: The SID of the Service that the resource is associated with - :rtype: unicode + payload, _, _ = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the UserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['service_sid'] + payload, _, _ = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def attributes(self): + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the UserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: """ - :returns: The JSON string that stores application-specific data - :rtype: unicode + 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['attributes'] + 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[UserInstance]: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + 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['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def role_sid(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Role assigned to the user - :rtype: unicode + Streams UserInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['role_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def identity(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The string that identifies the resource's User - :rtype: unicode + Asynchronously streams UserInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['identity'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def is_online(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: """ - :returns: Whether the User is actively connected to the Service instance and online - :rtype: bool + 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['is_online'] - @property - def is_notifiable(self): + return 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]: """ - :returns: Whether the User has a potentially valid Push Notification registration for the Service instance - :rtype: bool + 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['is_notifiable'] - @property - def date_created(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_created'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def date_updated(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Asynchronously lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_updated'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def joined_channels_count(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 number of Channels the User is a Member of - :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['joined_channels_count'] + 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 UserPage(self._version, response, solution=self._solution) + + async def 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: """ - :returns: The absolute URLs of the Channel and Binding resources related to the user - :rtype: unicode + 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 """ - return self._properties['links'] + 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 UserPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The absolute URL of the User resource - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers """ - return self._properties['url'] + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Fetch the UserInstance + Asynchronously retrieve a single page with response metadata - :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: ApiResponse with UserPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - 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, solution=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, solution=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 1bc9fd7a16..9d9ae604ef 100644 --- a/twilio/rest/chat/v2/service/user/user_binding.py +++ b/twilio/rest/chat/v2/service/user/user_binding.py @@ -1,450 +1,887 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +class UserBindingInstance(InstanceResource): + + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" - def __init__(self, version, service_sid, user_sid): + """ + :ivar sid: The unique string that we created to identify the User Binding resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User Binding resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the User Binding resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar endpoint: The unique endpoint identifier for the User Binding. The format of the value depends on the `binding_type`. + :ivar identity: The application-defined string that uniquely identifies the resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :ivar user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) with the User Binding resource. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :ivar credential_sid: The SID of the [Credential](https://www.twilio.com/docs/chat/rest/credential-resource) for the binding. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :ivar binding_type: + :ivar message_types: The [Programmable Chat message types](https://www.twilio.com/docs/chat/push-notification-configuration#push-types) the binding is subscribed to. + :ivar url: The absolute URL of the User Binding resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + user_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.endpoint: Optional[str] = payload.get("endpoint") + self.identity: Optional[str] = payload.get("identity") + self.user_sid: Optional[str] = payload.get("user_sid") + self.credential_sid: Optional[str] = payload.get("credential_sid") + self.binding_type: Optional["UserBindingInstance.BindingType"] = payload.get( + "binding_type" + ) + self.message_types: Optional[List[str]] = payload.get("message_types") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "sid": sid or self.sid, + } + + self._context: Optional[UserBindingContext] = None + + @property + def _proxy(self) -> "UserBindingContext": """ - Initialize the UserBindingList + 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 user_sid: The SID of the User with the binding + :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: twilio.rest.chat.v2.service.user.user_binding.UserBindingList - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingList + def delete(self) -> bool: """ - super(UserBindingList, self).__init__(version) + Deletes the UserBindingInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'user_sid': user_sid, } - self._uri = '/Services/{service_sid}/Users/{user_sid}/Bindings'.format(**self._solution) - def stream(self, binding_type=values.unset, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return self._proxy.delete() - :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) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserBindingInstance - :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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(binding_type=binding_type, page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserBindingInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, binding_type=values.unset, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists UserBindingInstance 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.delete_with_http_info() - :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) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserBindingInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(binding_type=binding_type, limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_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 + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserBindingInstance": """ - data = values.of({ - 'BindingType': serialize.map(binding_type, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Asynchronous coroutine to fetch the UserBindingInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return UserBindingPage(self._version, response, self._solution) + :returns: The fetched UserBindingInstance + """ + return await self._proxy.fetch_async() - def get_page(self, target_url): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a specific page of UserBindingInstance records from the API. - Request is executed immediately + Fetch the UserBindingInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingPage + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserBindingInstance with HTTP info - return UserBindingPage(self._version, response, self._solution) - def get(self, sid): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a UserBindingContext + return await self._proxy.fetch_with_http_info_async() - :param sid: The SID of the User Binding resource to fetch + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext + :returns: Machine friendly representation """ - return UserBindingContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - sid=sid, + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserBindingContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, user_sid: str, sid: str): + """ + Initialize the UserBindingContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the User Binding resource from. + :param user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) with the User Binding resource to fetch. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param sid: The SID of the User Binding resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Bindings/{sid}".format( + **self._solution ) - def __call__(self, sid): + def _delete(self) -> tuple: """ - Constructs a UserBindingContext + Internal helper for delete operation - :param sid: The SID of the User Binding resource to fetch + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return UserBindingContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - sid=sid, + Deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserBindingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + 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 '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserBindingInstance and return response metadata -class UserBindingPage(Page): - """ """ - def __init__(self, version, response, solution): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the UserBindingPage + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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 user_sid: The SID of the User with the binding + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingPage - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingPage + Returns: + tuple: (payload, status_code, headers) """ - super(UserBindingPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) + + headers["Accept"] = "application/json" - def get_instance(self, payload): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserBindingInstance: """ - Build an instance of UserBindingInstance + Fetch the UserBindingInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance + :returns: The fetched UserBindingInstance """ + payload, _, _ = self._fetch() 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Fetch the UserBindingInstance and return response metadata - :returns: Machine friendly representation - :rtype: str - """ - return '' + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) -class UserBindingContext(InstanceContext): - """ """ + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - def __init__(self, version, service_sid, user_sid, sid): + Returns: + tuple: (payload, status_code, headers) """ - Initialize the UserBindingContext - :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 + headers = values.of({}) - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - """ - super(UserBindingContext, self).__init__(version) + headers["Accept"] = "application/json" - # 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) + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + async def fetch_async(self) -> UserBindingInstance: """ - Fetch the UserBindingInstance + Asynchronous coroutine to fetch the UserBindingInstance + :returns: The fetched UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - + payload, _, _ = await self._fetch_async() 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"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the UserBindingInstance + Asynchronous coroutine to fetch the UserBindingInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 UserBindingInstance(InstanceResource): - """ """ +class UserBindingPage(Page): - class BindingType(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + def get_instance(self, payload: Dict[str, Any]) -> UserBindingInstance: + """ + Build an instance of UserBindingInstance - 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 payload: Payload response from the API + """ - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'user_sid': user_sid, - 'sid': sid or self._properties['sid'], - } + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_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: UserBindingContext for this UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext + :returns: Machine friendly representation """ - 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 + return "" - @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 +class UserBindingList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): """ - return self._properties['account_sid'] + Initialize the UserBindingList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the User Binding resources from. + :param user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) with the User Binding resources to read. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. - @property - def service_sid(self): """ - :returns: The SID of the Service that the resource is associated with - :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}/Bindings".format( + **self._solution + ) + + def stream( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserBindingInstance]: """ - return self._properties['service_sid'] + 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): + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :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 = self.page(binding_type=binding_type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserBindingInstance]: """ - return self._properties['date_created'] + 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_updated(self): + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :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 = await self.page_async( + binding_type=binding_type, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_updated'] + Streams UserBindingInstance and returns headers from first page - @property - def endpoint(self): + + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The unique endpoint identifier for the User Binding - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + binding_type=binding_type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['endpoint'] + Asynchronously streams UserBindingInstance and returns headers from first page - @property - def identity(self): + + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The string that identifies the resource's User - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + binding_type=binding_type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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): + :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 """ - :returns: The SID of the User with the binding - :rtype: unicode + + return list( + self.stream( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserBindingInstance]: """ - return self._properties['user_sid'] + 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. - @property - def credential_sid(self): + :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 """ - :returns: The SID of the Credential for the binding - :rtype: unicode + + return [ + record + async for record in await self.stream_async( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserBindingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserBindingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with UserBindingPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserBindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with UserBindingPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserBindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 04d1cb28ce..1c4fe1c849 100644 --- a/twilio/rest/chat/v2/service/user/user_channel.py +++ b/twilio/rest/chat/v2/service/user/user_channel.py @@ -1,485 +1,1203 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOTPARTICIPATING = "notParticipating" + + class NotificationLevel(object): + DEFAULT = "default" + MUTED = "muted" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User Channel resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the User Channel resource is associated with. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the User Channel resource belongs to. + :ivar user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) the User Channel belongs to. + :ivar member_sid: The SID of a [Member](https://www.twilio.com/docs/chat/rest/member-resource) that represents the User on the Channel. + :ivar status: + :ivar last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :ivar unread_messages_count: The number of unread Messages in the Channel for the User. Note that retrieving messages on a client endpoint does not mean that messages are consumed or read. See [Consumption Horizon feature](https://www.twilio.com/docs/chat/consumption-horizon) to learn how to mark messages as consumed. + :ivar links: The absolute URLs of the [Members](https://www.twilio.com/docs/chat/rest/member-resource), [Messages](https://www.twilio.com/docs/chat/rest/message-resource) , [Invites](https://www.twilio.com/docs/chat/rest/invite-resource) and, if it exists, the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) for the Channel. + :ivar url: The absolute URL of the User Channel resource. + :ivar notification_level: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + user_sid: str, + channel_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.member_sid: Optional[str] = payload.get("member_sid") + self.status: Optional["UserChannelInstance.ChannelStatus"] = payload.get( + "status" + ) + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + self.notification_level: Optional["UserChannelInstance.NotificationLevel"] = ( + payload.get("notification_level") + ) + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "channel_sid": channel_sid or self.channel_sid, + } + + self._context: Optional[UserChannelContext] = None + + @property + def _proxy(self) -> "UserChannelContext": """ - Initialize the UserChannelList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param user_sid: The SID of the User the User Channel belongs to + :returns: UserChannelContext for this UserChannelInstance + """ + if self._context is None: + self._context = UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return self._context - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelList + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - super(UserChannelList, self).__init__(version) + Deletes the UserChannelInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'user_sid': user_sid, } - self._uri = '/Services/{service_sid}/Users/{user_sid}/Channels'.format(**self._solution) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - Streams UserChannelInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the UserChannelInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance] + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - page = self.page(page_size=limits['page_size'], ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the UserChannelInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists UserChannelInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_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 delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserChannelInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance] + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_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, }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "UserChannelInstance": + """ + Asynchronous coroutine to fetch the UserChannelInstance - return UserChannelPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched UserChannelInstance """ - Retrieve a specific page of UserChannelInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserChannelInstance with HTTP info - :returns: Page of UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> "UserChannelInstance": + """ + Update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: The updated UserChannelInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, ) - return UserChannelPage(self._version, response, self._solution) + async def update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> "UserChannelInstance": + """ + Asynchronous coroutine to update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). - def get(self, channel_sid): + :returns: The updated UserChannelInstance """ - Constructs a UserChannelContext + return await self._proxy.update_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) - :param channel_sid: The SID of the Channel that has the User Channel to fetch + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserChannelInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers """ - return UserChannelContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - channel_sid=channel_sid, + return self._proxy.update_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: """ - Constructs a UserChannelContext + Asynchronous coroutine to update the UserChannelInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - 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_with_http_info_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, + ) -> tuple: """ - Build an instance of UserChannelInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - return UserChannelInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], + Deletes the UserChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the UserChannelInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __repr__(self): + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: """ - Provide a friendly representation + Internal async helper for delete operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (success_boolean, status_code, headers) """ - return '' + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + headers = values.of({}) -class UserChannelContext(InstanceContext): - """ """ + return await self._version.delete_with_response_info_async( + 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 x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :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: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return success - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - super(UserChannelContext, self).__init__(version) + Asynchronous coroutine that deletes the UserChannelInstance and return response metadata - # 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) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) - def fetch(self): + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", 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, ) + payload, _, _ = self._fetch() + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> UserChannelInstance: + """ + Asynchronous coroutine to fetch the UserChannelInstance + + :returns: The fetched UserChannelInstance + """ + payload, _, _ = await self._fetch_async() 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_with_http_info_async(self) -> ApiResponse: """ - Deletes the UserChannelInstance + Asynchronous coroutine to fetch the UserChannelInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + } + ) + headers = values.of({}) - def update(self, notification_level=values.unset, - last_consumed_message_index=values.unset, - last_consumption_timestamp=values.unset): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + 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_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + } + ) + headers = values.of({}) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: + """ + Asynchronous coroutine to update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: The updated UserChannelInstance + """ + payload, _, _ = await self._update_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide 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 UserChannelInstance(InstanceResource): - """ """ +class UserChannelPage(Page): - class ChannelStatus(object): - JOINED = "joined" - INVITED = "invited" - NOT_PARTICIPATING = "not_participating" + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: + """ + Build an instance of UserChannelInstance - class NotificationLevel(object): - DEFAULT = "default" - MUTED = "muted" + :param payload: Payload response from the API + """ + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) - def __init__(self, version, payload, service_sid, user_sid, 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) + return "" - # 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 +class UserChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserChannelList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the User Channel resources from. + :param user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) to read the User Channel resources from. This value can be either the `sid` or the `identity` of the User resource. + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'user_sid': user_sid, - 'channel_sid': channel_sid or self._properties['channel_sid'], + "service_sid": service_sid, + "user_sid": user_sid, } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Channels".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserChannelInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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: UserChannelContext for this UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = UserChannelContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - channel_sid=self._solution['channel_sid'], - ) - return self._context + 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[UserChannelInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Asynchronously streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserChannelInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['service_sid'] + Asynchronously streams UserChannelInstance and returns headers from first page - @property - def channel_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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The SID of the Channel the resource belongs to - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: """ - return self._properties['channel_sid'] + 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 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 User the User Channel belongs to - :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['user_sid'] + Asynchronously lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def member_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 User as a Member in the Channel - :rtype: unicode + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['member_sid'] + Lists UserChannelInstance and returns headers from first page - @property - def status(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: ApiResponse with list of instances, status code, and headers """ - :returns: The status of the User on the Channel - :rtype: UserChannelInstance.ChannelStatus + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['status'] + Asynchronously lists UserChannelInstance and returns headers from first page - @property - def last_consumed_message_index(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: ApiResponse with list of instances, status code, and headers """ - :returns: The index of the last Message in the Channel the Member has read - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['last_consumed_message_index'] + Retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately - @property - def unread_messages_count(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 number of unread Messages in the Channel for the User - :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, solution=self._solution) + + async def 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['unread_messages_count'] + Asynchronously retrieve a single page of UserChannelInstance 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 UserChannelInstance """ - :returns: Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel - :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 UserChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['links'] + Retrieve a single page with response metadata - @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: ApiResponse with UserChannelPage, status code, and headers """ - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['url'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with UserChannelPage, status code, and headers """ - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..fa71c46897 --- /dev/null +++ b/twilio/rest/chat/v3/channel.py @@ -0,0 +1,471 @@ +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.api_response import ApiResponse +from twilio.base.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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ChannelInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..5432e54944 --- /dev/null +++ b/twilio/rest/content/v1/content/__init__.py @@ -0,0 +1,3499 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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: + :ivar webview_size: + """ + + 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") + self.webview_size: Optional["ContentInstance.WebviewSizeType"] = ( + payload.get("webview_size") + ) + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + "code": self.code, + "webview_size": self.webview_size, + } + + 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 ContentUpdateRequest(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("timeSlots") + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "timeSlots": 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: + :ivar whatsapp_flows: + """ + + 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") + self.whatsapp_flows: Optional[ContentList.WhatsappFlows] = payload.get( + "whatsapp/flows" + ) + + 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 + ), + "whatsapp/flows": ( + self.whatsapp_flows.to_dict() + if self.whatsapp_flows 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 WhatsappFlows(object): + """ + :ivar body: + :ivar button_text: + :ivar subtitle: + :ivar media_url: + :ivar flow_id: + :ivar flow_token: + :ivar flow_first_page_id: + :ivar is_flow_first_page_endpoint: + """ + + 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.flow_id: Optional[str] = payload.get("flow_id") + self.flow_token: Optional[str] = payload.get("flow_token") + self.flow_first_page_id: Optional[str] = payload.get("flow_first_page_id") + self.is_flow_first_page_endpoint: Optional[bool] = payload.get( + "is_flow_first_page_endpoint" + ) + + def to_dict(self): + return { + "body": self.body, + "button_text": self.button_text, + "subtitle": self.subtitle, + "media_url": self.media_url, + "flow_id": self.flow_id, + "flow_token": self.flow_token, + "flow_first_page_id": self.flow_first_page_id, + "is_flow_first_page_endpoint": self.is_flow_first_page_endpoint, + } + + 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" + + class WebviewSizeType(object): + TALL = "TALL" + FULL = "FULL" + HALF = "HALF" + NONE = "NONE" + + """ + :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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ContentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ContentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ContentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ContentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update(self, content_update_request: ContentUpdateRequest) -> "ContentInstance": + """ + Update the ContentInstance + + :param content_update_request: + + :returns: The updated ContentInstance + """ + return self._proxy.update( + content_update_request=content_update_request, + ) + + async def update_async( + self, content_update_request: ContentUpdateRequest + ) -> "ContentInstance": + """ + Asynchronous coroutine to update the ContentInstance + + :param content_update_request: + + :returns: The updated ContentInstance + """ + return await self._proxy.update_async( + content_update_request=content_update_request, + ) + + def update_with_http_info( + self, content_update_request: ContentUpdateRequest + ) -> ApiResponse: + """ + Update the ContentInstance with HTTP info + + :param content_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + content_update_request=content_update_request, + ) + + async def update_with_http_info_async( + self, content_update_request: ContentUpdateRequest + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ContentInstance with HTTP info + + :param content_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + content_update_request=content_update_request, + ) + + @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: + :ivar webview_size: + """ + + 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") + self.webview_size: Optional["ContentInstance.WebviewSizeType"] = ( + payload.get("webview_size") + ) + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + "code": self.code, + "webview_size": self.webview_size, + } + + 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 ContentUpdateRequest(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("timeSlots") + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "timeSlots": 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: + :ivar whatsapp_flows: + """ + + 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") + self.whatsapp_flows: Optional[ContentList.WhatsappFlows] = payload.get( + "whatsapp/flows" + ) + + 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 + ), + "whatsapp/flows": ( + self.whatsapp_flows.to_dict() + if self.whatsapp_flows 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 WhatsappFlows(object): + """ + :ivar body: + :ivar button_text: + :ivar subtitle: + :ivar media_url: + :ivar flow_id: + :ivar flow_token: + :ivar flow_first_page_id: + :ivar is_flow_first_page_endpoint: + """ + + 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.flow_id: Optional[str] = payload.get("flow_id") + self.flow_token: Optional[str] = payload.get("flow_token") + self.flow_first_page_id: Optional[str] = payload.get("flow_first_page_id") + self.is_flow_first_page_endpoint: Optional[bool] = payload.get( + "is_flow_first_page_endpoint" + ) + + def to_dict(self): + return { + "body": self.body, + "button_text": self.button_text, + "subtitle": self.subtitle, + "media_url": self.media_url, + "flow_id": self.flow_id, + "flow_token": self.flow_token, + "flow_first_page_id": self.flow_first_page_id, + "is_flow_first_page_endpoint": self.is_flow_first_page_endpoint, + } + + 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 update. + """ + 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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ContentInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ContentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ContentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ContentInstance: + """ + Fetch the ContentInstance + + + :returns: The fetched ContentInstance + """ + payload, _, _ = self._fetch() + return ContentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ContentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ContentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ContentInstance: + """ + Asynchronous coroutine to fetch the ContentInstance + + + :returns: The fetched ContentInstance + """ + payload, _, _ = await self._fetch_async() + return ContentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ContentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ContentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, content_update_request: ContentUpdateRequest) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = content_update_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update(self, content_update_request: ContentUpdateRequest) -> ContentInstance: + """ + Update the ContentInstance + + :param content_update_request: + + :returns: The updated ContentInstance + """ + payload, _, _ = self._update(content_update_request=content_update_request) + return ContentInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, content_update_request: ContentUpdateRequest + ) -> ApiResponse: + """ + Update the ContentInstance and return response metadata + + :param content_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + content_update_request=content_update_request + ) + instance = ContentInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, content_update_request: ContentUpdateRequest + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = content_update_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, content_update_request: ContentUpdateRequest + ) -> ContentInstance: + """ + Asynchronous coroutine to update the ContentInstance + + :param content_update_request: + + :returns: The updated ContentInstance + """ + payload, _, _ = await self._update_async( + content_update_request=content_update_request + ) + return ContentInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, content_update_request: ContentUpdateRequest + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ContentInstance and return response metadata + + :param content_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + content_update_request=content_update_request + ) + instance = ContentInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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: + :ivar webview_size: + """ + + 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") + self.webview_size: Optional["ContentInstance.WebviewSizeType"] = ( + payload.get("webview_size") + ) + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + "code": self.code, + "webview_size": self.webview_size, + } + + 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 ContentUpdateRequest(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("timeSlots") + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "timeSlots": 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: + :ivar whatsapp_flows: + """ + + 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") + self.whatsapp_flows: Optional[ContentList.WhatsappFlows] = payload.get( + "whatsapp/flows" + ) + + 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 + ), + "whatsapp/flows": ( + self.whatsapp_flows.to_dict() + if self.whatsapp_flows 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 WhatsappFlows(object): + """ + :ivar body: + :ivar button_text: + :ivar subtitle: + :ivar media_url: + :ivar flow_id: + :ivar flow_token: + :ivar flow_first_page_id: + :ivar is_flow_first_page_endpoint: + """ + + 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.flow_id: Optional[str] = payload.get("flow_id") + self.flow_token: Optional[str] = payload.get("flow_token") + self.flow_first_page_id: Optional[str] = payload.get("flow_first_page_id") + self.is_flow_first_page_endpoint: Optional[bool] = payload.get( + "is_flow_first_page_endpoint" + ) + + def to_dict(self): + return { + "body": self.body, + "button_text": self.button_text, + "subtitle": self.subtitle, + "media_url": self.media_url, + "flow_id": self.flow_id, + "flow_token": self.flow_token, + "flow_first_page_id": self.flow_first_page_id, + "is_flow_first_page_endpoint": self.is_flow_first_page_endpoint, + } + + 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, content_create_request: ContentCreateRequest) -> ContentInstance: + """ + Create the ContentInstance + + :param content_create_request: + + :returns: The created ContentInstance + """ + payload, _, _ = self._create(content_create_request=content_create_request) + return ContentInstance(self._version, payload) + + def create_with_http_info( + self, content_create_request: ContentCreateRequest + ) -> ApiResponse: + """ + Create the ContentInstance and return response metadata + + :param content_create_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + content_create_request=content_create_request + ) + instance = ContentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, content_create_request: ContentCreateRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, content_create_request: ContentCreateRequest + ) -> ContentInstance: + """ + Asynchronously create the ContentInstance + + :param content_create_request: + + :returns: The created ContentInstance + """ + payload, _, _ = await self._create_async( + content_create_request=content_create_request + ) + return ContentInstance(self._version, payload) + + async def create_with_http_info_async( + self, content_create_request: ContentCreateRequest + ) -> ApiResponse: + """ + Asynchronously create the ContentInstance and return response metadata + + :param content_create_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + content_create_request=content_create_request + ) + instance = ContentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ContentInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ContentInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ContentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ContentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 update. + """ + 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 update. + """ + 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..2487ec6090 --- /dev/null +++ b/twilio/rest/content/v1/content/approval_create.py @@ -0,0 +1,229 @@ +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.api_response import ApiResponse + +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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, content_approval_request: ContentApprovalRequest + ) -> ApprovalCreateInstance: + """ + Create the ApprovalCreateInstance + + :param content_approval_request: + + :returns: The created ApprovalCreateInstance + """ + payload, _, _ = self._create(content_approval_request=content_approval_request) + return ApprovalCreateInstance( + self._version, payload, content_sid=self._solution["content_sid"] + ) + + def create_with_http_info( + self, content_approval_request: ContentApprovalRequest + ) -> ApiResponse: + """ + Create the ApprovalCreateInstance and return response metadata + + :param content_approval_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + content_approval_request=content_approval_request + ) + instance = ApprovalCreateInstance( + self._version, payload, content_sid=self._solution["content_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, content_approval_request: ContentApprovalRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, content_approval_request: ContentApprovalRequest + ) -> ApprovalCreateInstance: + """ + Asynchronously create the ApprovalCreateInstance + + :param content_approval_request: + + :returns: The created ApprovalCreateInstance + """ + payload, _, _ = await self._create_async( + content_approval_request=content_approval_request + ) + return ApprovalCreateInstance( + self._version, payload, content_sid=self._solution["content_sid"] + ) + + async def create_with_http_info_async( + self, content_approval_request: ContentApprovalRequest + ) -> ApiResponse: + """ + Asynchronously create the ApprovalCreateInstance and return response metadata + + :param content_approval_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + content_approval_request=content_approval_request + ) + instance = ApprovalCreateInstance( + self._version, payload, content_sid=self._solution["content_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..47b00a89ec --- /dev/null +++ b/twilio/rest/content/v1/content/approval_fetch.py @@ -0,0 +1,261 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ApprovalFetchInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApprovalFetchInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ApprovalFetchInstance: + """ + Fetch the ApprovalFetchInstance + + + :returns: The fetched ApprovalFetchInstance + """ + payload, _, _ = self._fetch() + return ApprovalFetchInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ApprovalFetchInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ApprovalFetchInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ApprovalFetchInstance: + """ + Asynchronous coroutine to fetch the ApprovalFetchInstance + + + :returns: The fetched ApprovalFetchInstance + """ + payload, _, _ = await self._fetch_async() + return ApprovalFetchInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApprovalFetchInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ApprovalFetchInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..73c009e1be --- /dev/null +++ b/twilio/rest/content/v1/content_and_approvals.py @@ -0,0 +1,472 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ContentAndApprovalsInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ContentAndApprovalsInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ContentAndApprovalsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ContentAndApprovalsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentAndApprovalsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ContentAndApprovalsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentAndApprovalsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ContentAndApprovalsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..a600809360 --- /dev/null +++ b/twilio/rest/content/v1/legacy_content.py @@ -0,0 +1,474 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams LegacyContentInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams LegacyContentInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists LegacyContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists LegacyContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with LegacyContentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = LegacyContentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with LegacyContentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = LegacyContentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..2584c2fd5d --- /dev/null +++ b/twilio/rest/content/v2/content.py @@ -0,0 +1,802 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams ContentInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams ContentInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists ContentInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists ContentInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ContentPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ContentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ContentPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ContentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..e383867e93 --- /dev/null +++ b/twilio/rest/content/v2/content_and_approvals.py @@ -0,0 +1,802 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams ContentAndApprovalsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams ContentAndApprovalsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists ContentAndApprovalsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists ContentAndApprovalsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ContentAndApprovalsPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ContentAndApprovalsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ContentAndApprovalsPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ContentAndApprovalsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..0a34545412 --- /dev/null +++ b/twilio/rest/conversations/ConversationsBase.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.conversations.v1 import V1 +from twilio.rest.conversations.v2 import V2 + + +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 + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Conversations + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Conversations + """ + 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/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..3c0864ec2f --- /dev/null +++ b/twilio/rest/conversations/v1/address_configuration.py @@ -0,0 +1,1610 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AddressConfigurationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddressConfigurationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AddressConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AddressConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the AddressConfigurationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AddressConfigurationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the AddressConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AddressConfigurationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddressConfigurationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AddressConfigurationInstance: + """ + Fetch the AddressConfigurationInstance + + + :returns: The fetched AddressConfigurationInstance + """ + payload, _, _ = self._fetch() + return AddressConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AddressConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AddressConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AddressConfigurationInstance: + """ + Asynchronous coroutine to fetch the AddressConfigurationInstance + + + :returns: The fetched AddressConfigurationInstance + """ + payload, _, _ = await self._fetch_async() + return AddressConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AddressConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AddressConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._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, + ) + return AddressConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the AddressConfigurationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = AddressConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + return AddressConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AddressConfigurationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = AddressConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + type=type, + address=address, + 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, + address_country=address_country, + ) + return AddressConfigurationInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the AddressConfigurationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + address=address, + 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, + address_country=address_country, + ) + instance = AddressConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + type=type, + address=address, + 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, + address_country=address_country, + ) + return AddressConfigurationInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the AddressConfigurationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + address=address, + 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, + address_country=address_country, + ) + instance = AddressConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AddressConfigurationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + type=type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AddressConfigurationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + type=type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AddressConfigurationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + type=type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AddressConfigurationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + type=type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with AddressConfigurationPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AddressConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with AddressConfigurationPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AddressConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..ec2a73badd --- /dev/null +++ b/twilio/rest/conversations/v1/configuration/__init__.py @@ -0,0 +1,528 @@ +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.api_response import ApiResponse +from twilio.base.instance_context 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ConfigurationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConfigurationInstance: + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = self._fetch() + return ConfigurationInstance( + self._version, + payload, + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConfigurationInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = await self._fetch_async() + return ConfigurationInstance( + self._version, + payload, + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConfigurationInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._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, + ) + return ConfigurationInstance(self._version, payload) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ConfigurationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + return ConfigurationInstance(self._version, payload) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..d286bba936 --- /dev/null +++ b/twilio/rest/conversations/v1/configuration/webhook.py @@ -0,0 +1,546 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + method=method, + filters=filters, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + target=target, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = self._fetch() + return WebhookInstance( + self._version, + payload, + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() + return WebhookInstance( + self._version, + payload, + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + method=method, + filters=filters, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + target=target, + ) + return WebhookInstance(self._version, payload) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the WebhookInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + method=method, + filters=filters, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + target=target, + ) + instance = WebhookInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + method=method, + filters=filters, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + target=target, + ) + return WebhookInstance(self._version, payload) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + method=method, + filters=filters, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + target=target, + ) + instance = WebhookInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 b1da4e7f33..808ab297e8 100644 --- a/twilio/rest/conversations/v1/conversation/__init__.py +++ b/twilio/rest/conversations/v1/conversation/__init__.py @@ -1,556 +1,1887 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): + INITIALIZING = "initializing" + 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, + } - def create(self, friendly_name=values.unset, date_created=values.unset, - date_updated=values.unset, messaging_service_sid=values.unset, - attributes=values.unset, x_twilio_webhook_enabled=values.unset): - """ - Create the ConversationInstance + self._context: Optional[ConversationContext] = None - :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.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + @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: 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, - }) - 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'], limits['page_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 delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - Lists ConversationInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the ConversationInstance with HTTP info - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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.conversations.v1.conversation.ConversationInstance] + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - Retrieve a single page of ConversationInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the ConversationInstance with HTTP info - :param str page_token: PageToken provided by the API - :param 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 - :returns: Page of ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationPage + :returns: ApiResponse with success boolean, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return ConversationPage(self._version, response, self._solution) + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def get_page(self, target_url): + def fetch(self) -> "ConversationInstance": """ - Retrieve a specific page of ConversationInstance records from the API. - Request is executed immediately + Fetch the ConversationInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationPage + :returns: The fetched ConversationInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ConversationPage(self._version, response, self._solution) + return self._proxy.fetch() - def get(self, sid): + async def fetch_async(self) -> "ConversationInstance": """ - Constructs a ConversationContext + Asynchronous coroutine to fetch the ConversationInstance - :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 """ - return ConversationContext(self._version, sid=sid, ) + return await self._proxy.fetch_async() - def __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a ConversationContext + Fetch the ConversationInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return ConversationContext(self._version, sid=sid, ) + return self._proxy.fetch_with_http_info() - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the ConversationInstance with HTTP info - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - return '' + return await self._proxy.fetch_with_http_info_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 -class ConversationPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :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 __init__(self, version, response, solution): + :returns: The updated ConversationInstance """ - Initialize the ConversationPage + 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 Version version: Version that contains the resource - :param Response response: Response from the API + 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: twilio.rest.conversations.v1.conversation.ConversationPage - :rtype: twilio.rest.conversations.v1.conversation.ConversationPage + :returns: The updated ConversationInstance """ - super(ConversationPage, self).__init__(version, response) + 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, + ) - # Path Solution - self._solution = solution + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ConversationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConversationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) - def get_instance(self, payload): + @property + def messages(self) -> MessageList: """ - Build an instance of ConversationInstance + Access the messages + """ + return self._proxy.messages - :param dict payload: Payload response from the API + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + return self._proxy.participants - :returns: twilio.rest.conversations.v1.conversation.ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationInstance + @property + def webhooks(self) -> WebhookList: """ - return ConversationInstance(self._version, payload, ) + Access the webhooks + """ + return self._proxy.webhooks - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class ConversationContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, sid): + def __init__(self, version: Version, sid: str): """ Initialize the ConversationContext - :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 + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. """ - super(ConversationContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Conversations/{sid}'.format(**self._solution) + self._solution = { + "sid": sid, + } + self._uri = "/Conversations/{sid}".format(**self._solution) - # Dependents - self._participants = None - self._messages = None - self._webhooks = None + self._messages: Optional[MessageList] = None + self._participants: Optional[ParticipantList] = None + self._webhooks: Optional[WebhookList] = None - def update(self, friendly_name=values.unset, date_created=values.unset, - date_updated=values.unset, attributes=values.unset, - messaging_service_sid=values.unset, - x_twilio_webhook_enabled=values.unset): + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: """ - 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.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + Internal helper for delete operation - :returns: The updated ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationInstance + Returns: + tuple: (success_boolean, status_code, 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, - }) - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + headers = values.of({}) - return ConversationInstance(self._version, payload, sid=self._solution['sid'], ) + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - def delete(self, x_twilio_webhook_enabled=values.unset): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ Deletes the ConversationInstance - :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 :returns: True if delete succeeds, False otherwise - :rtype: bool """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) - - def fetch(self): + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - Fetch the ConversationInstance + Deletes the ConversationInstance and return response metadata - :returns: The fetched ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - return ConversationInstance(self._version, payload, sid=self._solution['sid'], ) + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) - @property - def participants(self): + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: """ - Access the participants + Internal async helper for delete operation - :returns: twilio.rest.conversations.v1.conversation.participant.ParticipantList - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantList + Returns: + tuple: (success_boolean, status_code, headers) """ - if self._participants is None: - self._participants = ParticipantList(self._version, conversation_sid=self._solution['sid'], ) - return self._participants + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) - @property - def messages(self): + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Access the messages + Asynchronous coroutine that deletes the ConversationInstance - :returns: twilio.rest.conversations.v1.conversation.message.MessageList - :rtype: twilio.rest.conversations.v1.conversation.message.MessageList + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise """ - if self._messages is None: - self._messages = MessageList(self._version, conversation_sid=self._solution['sid'], ) - return self._messages + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return success - @property - def webhooks(self): + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - Access the webhooks + Asynchronous coroutine that deletes the ConversationInstance and return response metadata - :returns: twilio.rest.conversations.v1.conversation.webhook.WebhookList - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookList + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers """ - if self._webhooks is None: - self._webhooks = WebhookList(self._version, conversation_sid=self._solution['sid'], ) - return self._webhooks + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __repr__(self): + def _fetch(self) -> tuple: """ - Provide a friendly representation + Internal helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) -class ConversationInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, payload, sid=None): + def fetch(self) -> ConversationInstance: """ - Initialize the ConversationInstance + Fetch the ConversationInstance + - :returns: twilio.rest.conversations.v1.conversation.ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationInstance + :returns: The fetched ConversationInstance """ - super(ConversationInstance, self).__init__(version) + payload, _, _ = self._fetch() + return ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - # 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'), - '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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationInstance and return response metadata - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): + :returns: ApiResponse with instance, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, status_code, headers = self._fetch() + instance = ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: ConversationContext for this ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationContext + async def _fetch_async(self) -> tuple: """ - if self._context is None: - self._context = ConversationContext(self._version, sid=self._solution['sid'], ) - return self._context + Internal async helper for fetch operation - @property - def account_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The unique id of the Account responsible for this conversation. - :rtype: unicode + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConversationInstance: """ - return self._properties['account_sid'] + Asynchronous coroutine to fetch the ConversationInstance - @property - def chat_service_sid(self): + + :returns: The fetched ConversationInstance """ - :returns: The unique id of the Chat Service this conversation belongs to. - :rtype: unicode + payload, _, _ = await self._fetch_async() + return ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: """ - return self._properties['chat_service_sid'] + Asynchronous coroutine to fetch the ConversationInstance and return response metadata - @property - def messaging_service_sid(self): + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The unique id of the SMS Service this conversation belongs to. - :rtype: unicode + payload, status_code, headers = await self._fetch_async() + instance = ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, 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({}) + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._properties['messaging_service_sid'] + Update the ConversationInstance - @property - def sid(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 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 """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode + payload, _, _ = self._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, + ) + return ConversationInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ConversationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ConversationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, 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({}) + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 self._properties['sid'] + payload, _, _ = await self._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 ConversationInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConversationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ConversationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def friendly_name(self): + def messages(self) -> MessageList: """ - :returns: The human-readable name of this conversation. - :rtype: unicode + Access the messages """ - return self._properties['friendly_name'] + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["sid"], + ) + return self._messages @property - def attributes(self): + def participants(self) -> ParticipantList: """ - :returns: An optional string metadata field you can use to store any data you wish. - :rtype: unicode + Access the participants """ - return self._properties['attributes'] + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["sid"], + ) + return self._participants @property - def date_created(self): + def webhooks(self) -> WebhookList: """ - :returns: The date that this resource was created. - :rtype: datetime + Access the webhooks """ - return self._properties['date_created'] + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, + self._solution["sid"], + ) + return self._webhooks - @property - def date_updated(self): + def __repr__(self) -> str: """ - :returns: The date that this resource was last updated. - :rtype: datetime + Provide a friendly representation + + :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 url(self): + +class ConversationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConversationInstance: """ - :returns: An absolute URL for this conversation. - :rtype: unicode + Build an instance of ConversationInstance + + :param payload: Payload response from the API """ - return self._properties['url'] - @property - def links(self): + return ConversationInstance(self._version, payload) + + def __repr__(self) -> str: """ - :returns: Absolute URLs to access the Participants of this Conversation. - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['links'] + return "" + - def update(self, friendly_name=values.unset, date_created=values.unset, - date_updated=values.unset, attributes=values.unset, - messaging_service_sid=values.unset, - x_twilio_webhook_enabled=values.unset): +class ConversationList(ListResource): + + def __init__(self, version: Version): """ - Update the ConversationInstance + Initialize the ConversationList - :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.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Conversations" + + def _create( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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", + } + ) - :returns: The updated ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._proxy.update( + 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 + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, friendly_name=friendly_name, + unique_name=unique_name, date_created=date_created, date_updated=date_updated, + messaging_service_sid=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, + ) + return ConversationInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ConversationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, messaging_service_sid=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, + ) + instance = ConversationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=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, + ) + return ConversationInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ConversationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=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, + ) + instance = ConversationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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"], ) - def delete(self, x_twilio_webhook_enabled=values.unset): + 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]: """ - Deletes the 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 ConversationInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :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: True if delete succeeds, False otherwise - :rtype: bool + :returns: Generator that will yield up to limit results """ - return self._proxy.delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + 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"], + ) - def fetch(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: """ - Fetch the ConversationInstance + Streams ConversationInstance and returns headers from first page - :returns: The fetched ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationInstance + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._proxy.fetch() + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) - @property - def participants(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - Access the participants + Asynchronously streams ConversationInstance and returns headers from first page + + + :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: twilio.rest.conversations.v1.conversation.participant.ParticipantList - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantList + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._proxy.participants + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) - @property - def messages(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - Access the messages + Lists ConversationInstance 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.conversations.v1.conversation.message.MessageList - :rtype: twilio.rest.conversations.v1.conversation.message.MessageList + :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._proxy.messages + 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. - @property - def webhooks(self): + :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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists ConversationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists ConversationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - Access the webhooks + 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: twilio.rest.conversations.v1.conversation.webhook.WebhookList - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookList + :returns: Page of ConversationInstance """ - return self._proxy.webhooks + data = values.of( + { + "StartDate": start_date, + "EndDate": end_date, + "State": state, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationPage(self._version, response) + + async def page_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConversationPage: + """ + Asynchronously retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConversationInstance + """ + data = values.of( + { + "StartDate": start_date, + "EndDate": end_date, + "State": state, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationPage(self._version, response) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ConversationPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConversationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ConversationPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConversationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ConversationPage: + """ + Retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConversationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConversationPage: + """ + Asynchronously retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConversationPage(self._version, response) + + def get(self, sid: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. + """ + return ConversationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. + """ + return ConversationContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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.py b/twilio/rest/conversations/v1/conversation/message.py deleted file mode 100644 index fb7823ad5b..0000000000 --- a/twilio/rest/conversations/v1/conversation/message.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 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 MessageList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, conversation_sid): - """ - Initialize the MessageList - - :param Version version: Version that contains the resource - :param conversation_sid: The unique id of the Conversation for this message. - - :returns: twilio.rest.conversations.v1.conversation.message.MessageList - :rtype: twilio.rest.conversations.v1.conversation.message.MessageList - """ - super(MessageList, self).__init__(version) - - # Path Solution - self._solution = {'conversation_sid': conversation_sid, } - self._uri = '/Conversations/{conversation_sid}/Messages'.format(**self._solution) - - 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): - """ - Create 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 - - :returns: The created 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, - 'MediaSid': media_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, ) - - return MessageInstance(self._version, payload, conversation_sid=self._solution['conversation_sid'], ) - - def stream(self, limit=None, page_size=None): - """ - 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) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.conversations.v1.conversation.message.MessageInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists MessageInstance 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.conversations.v1.conversation.message.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): - """ - Retrieve a single page of MessageInstance 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 MessageInstance - :rtype: twilio.rest.conversations.v1.conversation.message.MessagePage - """ - data = values.of({'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) - - def get_page(self, target_url): - """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of MessageInstance - :rtype: twilio.rest.conversations.v1.conversation.message.MessagePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return MessagePage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a MessageContext - - :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, ) - - def __call__(self, sid): - """ - Constructs a MessageContext - - :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, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class MessagePage(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 MessagePage - - :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. - - :returns: twilio.rest.conversations.v1.conversation.message.MessagePage - :rtype: twilio.rest.conversations.v1.conversation.message.MessagePage - """ - super(MessagePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of 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 - """ - return MessageInstance(self._version, payload, conversation_sid=self._solution['conversation_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class MessageContext(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): - """ - Initialize the MessageContext - - :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 - """ - 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) - - 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): - """ - 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 - - :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, ) - - return MessageInstance( - self._version, - payload, - conversation_sid=self._solution['conversation_sid'], - sid=self._solution['sid'], - ) - - def delete(self, x_twilio_webhook_enabled=values.unset): - """ - Deletes the MessageInstance - - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) - - def fetch(self): - """ - Fetch the MessageInstance - - :returns: The fetched MessageInstance - :rtype: twilio.rest.conversations.v1.conversation.message.MessageInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return MessageInstance( - self._version, - payload, - conversation_sid=self._solution['conversation_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 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" - - 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'), - } - - # 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 - - :returns: MessageContext for this MessageInstance - :rtype: twilio.rest.conversations.v1.conversation.message.MessageContext - """ - if self._context is None: - self._context = MessageContext( - self._version, - conversation_sid=self._solution['conversation_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The unique id of the Account responsible for this message. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def conversation_sid(self): - """ - :returns: The unique id of the Conversation for this message. - :rtype: unicode - """ - return self._properties['conversation_sid'] - - @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'] - - @property - def author(self): - """ - :returns: The channel specific identifier of the message's author. - :rtype: unicode - """ - return self._properties['author'] - - @property - def body(self): - """ - :returns: The content of the message. - :rtype: unicode - """ - return self._properties['body'] - - @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'] - - @property - def attributes(self): - """ - :returns: A string metadata field you can use to store any data you wish. - :rtype: unicode - """ - return self._properties['attributes'] - - @property - def participant_sid(self): - """ - :returns: The unique id of messages's author participant. - :rtype: unicode - """ - return self._properties['participant_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 url(self): - """ - :returns: An absolute URL for this message. - :rtype: unicode - """ - return self._properties['url'] - - 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): - """ - 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 - - :returns: The updated MessageInstance - :rtype: twilio.rest.conversations.v1.conversation.message.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, - ) - - def delete(self, x_twilio_webhook_enabled=values.unset): - """ - Deletes the MessageInstance - - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) - - def fetch(self): - """ - Fetch the MessageInstance - - :returns: The fetched MessageInstance - :rtype: twilio.rest.conversations.v1.conversation.message.MessageInstance - """ - 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/conversations/v1/conversation/message/__init__.py b/twilio/rest/conversations/v1/conversation/message/__init__.py new file mode 100644 index 0000000000..4d1345715e --- /dev/null +++ b/twilio/rest/conversations/v1/conversation/message/__init__.py @@ -0,0 +1,1647 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.conversations.v1.conversation.message.delivery_receipt import ( + DeliveryReceiptList, +) + + +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this message. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar index: The index of the message within the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource). Indices may skip numbers, but will always be in order of when the message was received. + :ivar author: The channel specific identifier of the message's author. Defaults to `system`. + :ivar body: The content of the message, can be up to 1,600 characters long. + :ivar media: An array of objects that describe the Message's media, if the message contains media. Each object contains these fields: `content_type` with the MIME type of the media, `filename` with the name of the media, `sid` with the SID of the Media resource, and `size` with the media object's file size in bytes. If the Message has no media, this value is `null`. + :ivar attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar participant_sid: The unique ID of messages's author participant. Null in case of `system` sent message. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :ivar url: An absolute API resource API URL for this message. + :ivar delivery: An object that contains the summary of delivery statuses for the message to non-chat participants. + :ivar links: Contains an absolute API resource URL to access the delivery & read receipts of this message. + :ivar content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.sid: Optional[str] = payload.get("sid") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.author: Optional[str] = payload.get("author") + self.body: Optional[str] = payload.get("body") + self.media: Optional[List[Dict[str, object]]] = payload.get("media") + self.attributes: Optional[str] = payload.get("attributes") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.delivery: Optional[Dict[str, object]] = payload.get("delivery") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.content_sid: Optional[str] = payload.get("content_sid") + + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + + @property + def delivery_receipts(self) -> DeliveryReceiptList: + """ + Access the delivery_receipts + """ + return self._proxy.delivery_receipts + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessageContext(InstanceContext): + + def __init__(self, version: Version, conversation_sid: str, sid: str): + """ + Initialize the MessageContext + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Messages/{sid}".format( + **self._solution + ) + + self._delivery_receipts: Optional[DeliveryReceiptList] = None + + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + 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 + """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return success + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + payload, _, _ = self._fetch() + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + payload, _, _ = await self._fetch_async() + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._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, + ) + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def delivery_receipts(self) -> DeliveryReceiptList: + """ + Access the delivery_receipts + """ + if self._delivery_receipts is None: + self._delivery_receipts = DeliveryReceiptList( + self._version, + self._solution["conversation_sid"], + self._solution["sid"], + ) + return self._delivery_receipts + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + + return MessageInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MessageList(ListResource): + + def __init__(self, version: Version, conversation_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for messages. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + } + self._uri = "/Conversations/{conversation_sid}/Messages".format( + **self._solution + ) + + def _create( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) + return MessageInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) + instance = MessageInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) + return MessageInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) + instance = MessageInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MessageInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MessageInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MessageInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + order=order, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MessageInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with MessagePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with MessagePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return MessageContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return MessageContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py b/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py new file mode 100644 index 0000000000..ffebce0840 --- /dev/null +++ b/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py @@ -0,0 +1,727 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DeliveryReceiptInstance(InstanceResource): + + class DeliveryStatus(object): + READ = "read" + FAILED = "failed" + DELIVERED = "delivered" + UNDELIVERED = "undelivered" + SENT = "sent" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this participant. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar message_sid: The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to + :ivar channel_message_sid: A messaging channel-specific identifier for the message delivered to participant e.g. `SMxx` for SMS, `WAxx` for Whatsapp etc. + :ivar participant_sid: The unique ID of the participant the delivery receipt belongs to. + :ivar status: + :ivar error_code: The message [delivery error code](https://www.twilio.com/docs/sms/api/message-resource#delivery-related-errors) for a `failed` status, + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. `null` if the delivery receipt has not been updated. + :ivar url: An absolute API resource URL for this delivery receipt. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_sid: str, + message_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.sid: Optional[str] = payload.get("sid") + self.message_sid: Optional[str] = payload.get("message_sid") + self.channel_message_sid: Optional[str] = payload.get("channel_message_sid") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.status: Optional["DeliveryReceiptInstance.DeliveryStatus"] = payload.get( + "status" + ) + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "conversation_sid": conversation_sid, + "message_sid": message_sid, + "sid": sid or self.sid, + } + + self._context: Optional[DeliveryReceiptContext] = None + + @property + def _proxy(self) -> "DeliveryReceiptContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DeliveryReceiptContext for this DeliveryReceiptInstance + """ + if self._context is None: + self._context = DeliveryReceiptContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "DeliveryReceiptInstance": + """ + Fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DeliveryReceiptInstance": + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DeliveryReceiptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DeliveryReceiptContext(InstanceContext): + + def __init__( + self, version: Version, conversation_sid: str, message_sid: str, sid: str + ): + """ + Initialize the DeliveryReceiptContext + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :param message_sid: The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "message_sid": message_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Messages/{message_sid}/Receipts/{sid}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DeliveryReceiptInstance: + """ + Fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + payload, _, _ = self._fetch() + return DeliveryReceiptInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DeliveryReceiptInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DeliveryReceiptInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DeliveryReceiptInstance: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + payload, _, _ = await self._fetch_async() + return DeliveryReceiptInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DeliveryReceiptInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 DeliveryReceiptPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DeliveryReceiptInstance: + """ + Build an instance of DeliveryReceiptInstance + + :param payload: Payload response from the API + """ + + return DeliveryReceiptInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DeliveryReceiptList(ListResource): + + def __init__(self, version: Version, conversation_sid: str, message_sid: str): + """ + Initialize the DeliveryReceiptList + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :param message_sid: The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "message_sid": message_sid, + } + self._uri = ( + "/Conversations/{conversation_sid}/Messages/{message_sid}/Receipts".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DeliveryReceiptInstance]: + """ + Streams DeliveryReceiptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DeliveryReceiptInstance]: + """ + Asynchronously streams DeliveryReceiptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DeliveryReceiptInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DeliveryReceiptInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DeliveryReceiptInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DeliveryReceiptInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DeliveryReceiptPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DeliveryReceiptPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DeliveryReceiptPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DeliveryReceiptPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, sid: str) -> DeliveryReceiptContext: + """ + Constructs a DeliveryReceiptContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return DeliveryReceiptContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> DeliveryReceiptContext: + """ + Constructs a DeliveryReceiptContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return DeliveryReceiptContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v1/conversation/participant.py b/twilio/rest/conversations/v1/conversation/participant.py index a150893431..0600512c97 100644 --- a/twilio/rest/conversations/v1/conversation/participant.py +++ b/twilio/rest/conversations/v1/conversation/participant.py @@ -1,501 +1,1650 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this participant. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this participant. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar messaging_binding: Information about how this participant exchanges messages with the conversation. A JSON parameter consisting of type and address fields of the participant. + :ivar role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar url: An absolute API resource URL for this participant. + :ivar last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :ivar last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.sid: Optional[str] = payload.get("sid") + self.identity: Optional[str] = payload.get("identity") + self.attributes: Optional[str] = payload.get("attributes") + self.messaging_binding: Optional[Dict[str, object]] = payload.get( + "messaging_binding" + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.last_read_message_index: Optional[int] = deserialize.integer( + payload.get("last_read_message_index") + ) + self.last_read_timestamp: Optional[str] = payload.get("last_read_timestamp") + + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + + self._context: Optional[ParticipantContext] = None - def __init__(self, version, conversation_sid): + @property + def _proxy(self) -> "ParticipantContext": """ - Initialize the ParticipantList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param conversation_sid: The unique id of the Conversation for this participant. + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.conversations.v1.conversation.participant.ParticipantList - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantList + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - super(ParticipantList, self).__init__(version) + Deletes the ParticipantInstance - # Path Solution - self._solution = {'conversation_sid': conversation_sid, } - self._uri = '/Conversations/{conversation_sid}/Participants'.format(**self._solution) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - 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, - x_twilio_webhook_enabled=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the ParticipantInstance + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - :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 ParticipantInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance - :returns: The created ParticipantInstance - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantInstance + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise """ - 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, - }) - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ParticipantInstance with HTTP info - return ParticipantInstance( - self._version, - payload, - conversation_sid=self._solution['conversation_sid'], + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) - def stream(self, limit=None, page_size=None): + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - 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 with HTTP info - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "ParticipantInstance": + """ + Fetch the ParticipantInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, 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 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) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance - :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 await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of ParticipantInstance records from the API. - Request is executed immediately + Fetch the ParticipantInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info - return ParticipantPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of ParticipantInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + 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 - :returns: Page of ParticipantInstance - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantPage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return ParticipantPage(self._version, response, self._solution) + 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. - def get(self, sid): + :returns: The updated ParticipantInstance """ - Constructs a ParticipantContext + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + identity=identity, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ParticipantInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + identity=identity, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + identity=identity, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ParticipantContext(InstanceContext): + + def __init__(self, version: Version, conversation_sid: str, sid: str): + """ + Initialize the ParticipantContext + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this participant. :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) - :returns: twilio.rest.conversations.v1.conversation.participant.ParticipantContext - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantContext + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Participants/{sid}".format( + **self._solution + ) + + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: """ - return ParticipantContext( - self._version, - conversation_sid=self._solution['conversation_sid'], - sid=sid, + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } ) - def __call__(self, sid): + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Constructs a ParticipantContext + Deletes the ParticipantInstance - :param sid: A 34 character string that uniquely identifies this resource. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.conversations.v1.conversation.participant.ParticipantContext - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantContext + :returns: True if delete succeeds, False otherwise """ - return ParticipantContext( - self._version, - conversation_sid=self._solution['conversation_sid'], - sid=sid, + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ParticipantInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __repr__(self): + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: """ - Provide a friendly representation + Internal async helper for delete operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (success_boolean, status_code, headers) """ - 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 await self._version.delete_with_response_info_async( + 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) + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return success - # Path Solution - self._solution = solution + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance and return response metadata - def get_instance(self, payload): + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers """ - Build an instance of ParticipantInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> 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 """ + payload, _, _ = self._fetch() return ParticipantInstance( self._version, payload, - conversation_sid=self._solution['conversation_sid'], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def fetch_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Fetch the ParticipantInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - return '' + payload, status_code, headers = self._fetch() + instance = ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation -class ParticipantContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + Returns: + tuple: (payload, status_code, headers) + """ - def __init__(self, version, conversation_sid, sid): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ParticipantInstance: """ - Initialize the ParticipantContext + Asynchronous coroutine to fetch the ParticipantInstance - :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. - :returns: twilio.rest.conversations.v1.conversation.participant.ParticipantContext - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantContext + :returns: The fetched ParticipantInstance + """ + payload, _, _ = await self._fetch_async() + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: """ - super(ParticipantContext, self).__init__(version) + Asynchronous coroutine to fetch the ParticipantInstance and return response metadata - # Path Solution - self._solution = {'conversation_sid': conversation_sid, 'sid': sid, } - self._uri = '/Conversations/{conversation_sid}/Participants/{sid}'.format(**self._solution) - def update(self, date_created=values.unset, date_updated=values.unset, - attributes=values.unset, x_twilio_webhook_enabled=values.unset): + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 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, - }) - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + payload, _, _ = self._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, + ) + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ParticipantInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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 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): - """ - Deletes the ParticipantInstance + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param ParticipantInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Machine friendly representation """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) - def fetch(self): +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: """ - Fetch the ParticipantInstance + Build an instance of ParticipantInstance - :returns: The fetched ParticipantInstance - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantInstance + :param payload: Payload response from the API """ - payload = self._version.fetch(method='GET', uri=self._uri, ) return ParticipantInstance( - self._version, - payload, - conversation_sid=self._solution['conversation_sid'], - sid=self._solution['sid'], + self._version, payload, conversation_sid=self._solution["conversation_sid"] ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a 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 ParticipantInstance(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" +class ParticipantList(ListResource): - def __init__(self, version, payload, conversation_sid, sid=None): + def __init__(self, version: Version, conversation_sid: str): """ - Initialize the ParticipantInstance + Initialize the ParticipantList + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for participants. - :returns: twilio.rest.conversations.v1.conversation.participant.ParticipantInstance - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantInstance """ - super(ParticipantInstance, self).__init__(version) + super().__init__(version) - # 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'), - '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 = { + "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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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", + } + ) - # Context - self._context = None - self._solution = {'conversation_sid': conversation_sid, 'sid': sid or self._properties['sid'], } + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def _proxy(self): + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - 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 ParticipantInstance - :returns: ParticipantContext for this ParticipantInstance - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantContext + :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 """ - if self._context is None: - self._context = ParticipantContext( - self._version, - conversation_sid=self._solution['conversation_sid'], - sid=self._solution['sid'], - ) - return self._context + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) + return ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) - @property - def account_sid(self): + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ParticipantInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) + instance = ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - :returns: The unique id of the Account responsible for this participant. - :rtype: unicode + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) + return ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ParticipantInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) + instance = ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: """ - return self._properties['account_sid'] + 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. - @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 participant. - :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[ParticipantInstance]: """ - return self._properties['conversation_sid'] + 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. - @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: A 34 character string that uniquely identifies this resource. - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['sid'] + Streams ParticipantInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: A unique string identifier for the conversation participant as Chat User. - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['identity'] + Asynchronously streams ParticipantInstance and returns headers from first page - @property - def attributes(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: An optional string metadata field you can use to store any data you wish. - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: """ - return self._properties['attributes'] + 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 messaging_binding(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: Information about how this participant exchanges messages with the conversation. - :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[ParticipantInstance]: """ - return self._properties['messaging_binding'] + 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 date_created(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The date that this resource was created. - :rtype: datetime + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_created'] + Lists ParticipantInstance and returns headers from first page - @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: ApiResponse with list of instances, status code, and headers """ - :returns: The date that this resource was last updated. - :rtype: datetime + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously lists ParticipantInstance and returns headers from first page - @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: ApiResponse with list of instances, status code, and headers """ - :returns: An absolute URL for this participant. - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['url'] + 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 - def update(self, date_created=values.unset, date_updated=values.unset, - attributes=values.unset, x_twilio_webhook_enabled=values.unset): + :returns: Page of ParticipantInstance """ - Update the ParticipantInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :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 ParticipantInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: The updated ParticipantInstance - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantInstance + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, solution=self._solution) + + async def 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._proxy.update( - date_created=date_created, - date_updated=date_updated, - attributes=attributes, - x_twilio_webhook_enabled=x_twilio_webhook_enabled, + 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, + } ) - def delete(self, x_twilio_webhook_enabled=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 ParticipantPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the ParticipantInstance + Retrieve a single page with response metadata - :param ParticipantInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :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: ApiResponse with ParticipantPage, status code, and headers """ - return self._proxy.delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + data = values.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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Fetch the ParticipantInstance + Asynchronously retrieve a single page with response metadata - :returns: The fetched ParticipantInstance - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantInstance + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return ParticipantContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return ParticipantContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 2f55df26d6..3140fd846c 100644 --- a/twilio/rest/conversations/v1/conversation/webhook.py +++ b/twilio/rest/conversations/v1/conversation/webhook.py @@ -1,483 +1,1349 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + + class Method(object): + GET = "get" + POST = "post" + + class Target(object): + WEBHOOK = "webhook" + TRIGGER = "trigger" + STUDIO = "studio" + + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + :ivar target: The target of this webhook: `webhook`, `studio`, `trigger` + :ivar url: An absolute API resource URL for this webhook. + :ivar configuration: The configuration of this webhook. Is defined based on target. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.target: Optional[str] = payload.get("target") + self.url: Optional[str] = payload.get("url") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + + self._context: Optional[WebhookContext] = None - def __init__(self, version, conversation_sid): + @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 conversation_sid: The unique id of the Conversation for this webhook. + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.conversations.v1.conversation.webhook.WebhookList - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookList + def delete(self) -> bool: """ - super(WebhookList, self).__init__(version) + Deletes the WebhookInstance - # Path Solution - self._solution = {'conversation_sid': conversation_sid, } - self._uri = '/Conversations/{conversation_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() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.conversations.v1.conversation.webhook.WebhookInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "WebhookInstance": """ - Retrieve a single page of WebhookInstance records from the API. - Request is executed immediately + 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.conversations.v1.conversation.webhook.WebhookPage + :returns: The fetched WebhookInstance """ - 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) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance - return WebhookPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched WebhookInstance """ - Retrieve a specific page of WebhookInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info - :returns: Page of WebhookInstance - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info - return WebhookPage(self._version, response, self._solution) - 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): + :returns: ApiResponse with instance, status code, and headers """ - Create the WebhookInstance + return await self._proxy.fetch_with_http_info_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 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. + :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 created WebhookInstance - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookInstance + :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": """ - 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, - }) + Asynchronous coroutine to update the WebhookInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :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. - return WebhookInstance(self._version, payload, conversation_sid=self._solution['conversation_sid'], ) + :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 get(self, sid): + def update_with_http_info( + 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, + ) -> ApiResponse: """ - Constructs a WebhookContext + Update the WebhookInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WebhookContext(self._version, conversation_sid=self._solution['conversation_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: """ - Constructs a WebhookContext + Asynchronous coroutine to update the WebhookInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WebhookContext(self._version, conversation_sid=self._solution['conversation_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of WebhookInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.conversations.v1.conversation.webhook.WebhookInstance - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return WebhookInstance(self._version, payload, conversation_sid=self._solution['conversation_sid'], ) + Deletes the WebhookInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the WebhookInstance and return response metadata -class WebhookContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, conversation_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the WebhookContext + Internal async helper for delete operation - :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: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.conversations.v1.conversation.webhook.WebhookContext - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookContext + async def delete_async(self) -> bool: """ - super(WebhookContext, self).__init__(version) + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance and return response metadata - # Path Solution - self._solution = {'conversation_sid': conversation_sid, 'sid': sid, } - self._uri = '/Conversations/{conversation_sid}/Webhooks/{sid}'.format(**self._solution) - def fetch(self): + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: """ Fetch the WebhookInstance + :returns: The fetched WebhookInstance - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() 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"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation - 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: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + return WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the WebhookInstance and return response metadata - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + instance = WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) 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_with_http_info_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, + ) -> ApiResponse: """ - Deletes the WebhookInstance + Asynchronous coroutine to update the WebhookInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + instance = WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 + """ - def __init__(self, version, payload, conversation_sid, sid=None): + return WebhookInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + 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 "" + + +class WebhookList(ListResource): - # 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')), + def __init__(self, version: Version, conversation_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, } + self._uri = "/Conversations/{conversation_sid}/Webhooks".format( + **self._solution + ) - # Context - self._context = None - self._solution = {'conversation_sid': conversation_sid, 'sid': sid or self._properties['sid'], } + 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, + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - 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.conversation.webhook.WebhookContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - if self._context is None: - self._context = WebhookContext( - self._version, - conversation_sid=self._solution['conversation_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the WebhookInstance - @property - def sid(self): + :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: A 34 character string that uniquely identifies this resource. - :rtype: unicode + payload, _, _ = self._create( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) + return WebhookInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['sid'] + Create the WebhookInstance and return response metadata - @property - def account_sid(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The unique id of the Account responsible for this conversation. - :rtype: unicode + payload, status_code, headers = self._create( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) + instance = WebhookInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for create operation - @property - def conversation_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The unique id of the Conversation for this webhook. - :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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._properties['conversation_sid'] + Asynchronously create the WebhookInstance - @property - def target(self): + :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 target of this webhook. - :rtype: unicode + payload, _, _ = await self._create_async( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) + return WebhookInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['target'] + Asynchronously create the WebhookInstance and return response metadata - @property - def url(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: An absolute URL for this webhook. - :rtype: unicode + payload, status_code, headers = await self._create_async( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) + instance = WebhookInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebhookInstance]: """ - return self._properties['url'] + 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 configuration(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 configuration of this webhook. - :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[WebhookInstance]: """ - return self._properties['configuration'] + 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 date_created(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The date that 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_created'] + Streams WebhookInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The date that this resource was last updated. - :rtype: datetime + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_updated'] + Asynchronously streams WebhookInstance and returns headers from first page + - 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: tuple of (generator, status_code, headers) where generator yields instances """ - Fetch the WebhookInstance + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :returns: The fetched WebhookInstance - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookInstance + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: """ - return self._proxy.fetch() + 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) - 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: list that will contain up to limit results """ - 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. + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: The updated WebhookInstance - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookInstance + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[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, + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists WebhookInstance and returns headers from first page + - 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: ApiResponse with list of instances, status code, and headers """ - Deletes the WebhookInstance + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 - :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 WebhookInstance """ - 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 WebhookPage(self._version, response, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return WebhookContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __call__(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return WebhookContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..76e25061e5 --- /dev/null +++ b/twilio/rest/conversations/v1/conversation_with_participants.py @@ -0,0 +1,449 @@ +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.api_response import ApiResponse + +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): + INITIALIZING = "initializing" + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=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=participant, + ) + return ConversationWithParticipantsInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ConversationWithParticipantsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=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=participant, + ) + instance = ConversationWithParticipantsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=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=participant, + ) + return ConversationWithParticipantsInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ConversationWithParticipantsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=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=participant, + ) + instance = ConversationWithParticipantsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..a1aabe7bdd --- /dev/null +++ b/twilio/rest/conversations/v1/credential.py @@ -0,0 +1,1330 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + payload, _, _ = self._fetch() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + payload, _, _ = await self._fetch_async() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CredentialInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the CredentialInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..9d6fc2566b --- /dev/null +++ b/twilio/rest/conversations/v1/participant_conversation.py @@ -0,0 +1,574 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantConversationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, address=address, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantConversationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, address=address, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantConversationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantConversationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ParticipantConversationPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantConversationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ParticipantConversationPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantConversationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..f0e9160bf5 --- /dev/null +++ b/twilio/rest/conversations/v1/role.py @@ -0,0 +1,1035 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + permission=permission, + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + payload, _, _ = self._fetch() + return RoleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + payload, _, _ = await self._fetch_async() + return RoleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, permission: List[str]) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(permission=permission) + return RoleInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(permission=permission) + instance = RoleInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, permission: List[str]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(permission=permission) + return RoleInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(permission=permission) + instance = RoleInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, 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 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] + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + return RoleInstance(self._version, payload) + + def create_with_http_info( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Create the RoleInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + return RoleInstance(self._version, payload) + + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Asynchronously create the RoleInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RoleInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RoleInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RolePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RolePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..e4e33fc15e --- /dev/null +++ b/twilio/rest/conversations/v1/service/__init__.py @@ -0,0 +1,1010 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(friendly_name=friendly_name) + return ServiceInstance(self._version, payload) + + def create_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :param friendly_name: The human-readable name of this service, limited to 256 characters. Optional. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return ServiceInstance(self._version, payload) + + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :param friendly_name: The human-readable name of this service, limited to 256 characters. Optional. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..095e307625 --- /dev/null +++ b/twilio/rest/conversations/v1/service/binding.py @@ -0,0 +1,874 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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" + TWILSOCK = "twilsock" + + """ + :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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BindingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BindingInstance: + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + payload, _, _ = self._fetch() + return BindingInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BindingInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + payload, _, _ = await self._fetch_async() + return BindingInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BindingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BindingInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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`, `fcm`, or `twilsock`. 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`, `fcm`, or `twilsock`. 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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`, `fcm`, or `twilsock`. 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`, `fcm`, or `twilsock`. 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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`, `fcm`, or `twilsock`. 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, solution=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`, `fcm`, or `twilsock`. 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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. 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: ApiResponse with BindingPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. 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: ApiResponse with BindingPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..4cdc9de636 --- /dev/null +++ b/twilio/rest/conversations/v1/service/configuration/__init__.py @@ -0,0 +1,585 @@ +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.api_response import ApiResponse +from twilio.base.instance_context 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ConfigurationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConfigurationInstance: + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = self._fetch() + return ConfigurationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConfigurationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = await self._fetch_async() + return ConfigurationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConfigurationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._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, + ) + return ConfigurationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ConfigurationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ConfigurationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + return ConfigurationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ConfigurationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..e646dbe7b9 --- /dev/null +++ b/twilio/rest/conversations/v1/service/configuration/notification.py @@ -0,0 +1,817 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NotificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NotificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the NotificationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the NotificationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> NotificationInstance: + """ + Fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + payload, _, _ = self._fetch() + return NotificationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NotificationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = NotificationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> NotificationInstance: + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + payload, _, _ = await self._fetch_async() + return NotificationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NotificationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = NotificationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._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, + ) + return NotificationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the NotificationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = NotificationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + return NotificationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the NotificationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = NotificationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..eee7e3f74e --- /dev/null +++ b/twilio/rest/conversations/v1/service/configuration/webhook.py @@ -0,0 +1,550 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = self._fetch() + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) + return WebhookInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the WebhookInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) + instance = WebhookInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) + return WebhookInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) + instance = WebhookInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..0dcfd00023 --- /dev/null +++ b/twilio/rest/conversations/v1/service/conversation/__init__.py @@ -0,0 +1,1943 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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" + INITIALIZING = "initializing" + + 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 delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ConversationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConversationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + 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 + """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ConversationInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return success + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConversationInstance: + """ + Fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + payload, _, _ = self._fetch() + return ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConversationInstance: + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + payload, _, _ = await self._fetch_async() + return ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, 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({}) + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._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, + ) + return ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ConversationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, 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({}) + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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 ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConversationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + date_created=date_created, + date_updated=date_updated, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + return ConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ConversationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + date_created=date_created, + date_updated=date_updated, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + instance = ConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + date_created=date_created, + date_updated=date_updated, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + return ConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ConversationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + date_created=date_created, + date_updated=date_updated, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + instance = ConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams ConversationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams ConversationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists ConversationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists ConversationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ConversationPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConversationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ConversationPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConversationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..6c4e26231b --- /dev/null +++ b/twilio/rest/conversations/v1/service/conversation/message/__init__.py @@ -0,0 +1,1688 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + 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 + """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return success + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + payload, _, _ = self._fetch() + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + payload, _, _ = await self._fetch_async() + 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._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, + ) + 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_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) + instance = MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) + instance = MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MessageInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MessageInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MessageInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + order=order, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MessageInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with MessagePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with MessagePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..d729edcd52 --- /dev/null +++ b/twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py @@ -0,0 +1,752 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DeliveryReceiptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DeliveryReceiptInstance: + """ + Fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + payload, _, _ = self._fetch() + 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DeliveryReceiptInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = 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"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DeliveryReceiptInstance: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + payload, _, _ = await self._fetch_async() + 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = 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"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DeliveryReceiptInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DeliveryReceiptInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DeliveryReceiptInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DeliveryReceiptInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DeliveryReceiptPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DeliveryReceiptPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DeliveryReceiptPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DeliveryReceiptPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..960f36fd16 --- /dev/null +++ b/twilio/rest/conversations/v1/service/conversation/participant.py @@ -0,0 +1,1690 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ParticipantInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + 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 + """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ParticipantInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return success + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = self._fetch() + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = await self._fetch_async() + 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._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, + ) + 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_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ParticipantInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ParticipantInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) + instance = ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ParticipantInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) + instance = ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..d95e4d364e --- /dev/null +++ b/twilio/rest/conversations/v1/service/conversation/webhook.py @@ -0,0 +1,1389 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = self._fetch() + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() + 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + 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_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the WebhookInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the WebhookInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the WebhookInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams WebhookInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams WebhookInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..b6305a6aae --- /dev/null +++ b/twilio/rest/conversations/v1/service/conversation_with_participants.py @@ -0,0 +1,474 @@ +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.api_response import ApiResponse + +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): + INITIALIZING = "initializing" + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=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=participant, + ) + return ConversationWithParticipantsInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ConversationWithParticipantsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=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=participant, + ) + instance = ConversationWithParticipantsInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=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=participant, + ) + return ConversationWithParticipantsInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ConversationWithParticipantsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=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=participant, + ) + instance = ConversationWithParticipantsInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..790e753f20 --- /dev/null +++ b/twilio/rest/conversations/v1/service/participant_conversation.py @@ -0,0 +1,603 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantConversationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, address=address, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantConversationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, address=address, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantConversationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantConversationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution + ) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ParticipantConversationPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantConversationPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ParticipantConversationPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantConversationPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..f7373513a0 --- /dev/null +++ b/twilio/rest/conversations/v1/service/role.py @@ -0,0 +1,1086 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + permission=permission, + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + payload, _, _ = self._fetch() + return RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + payload, _, _ = await self._fetch_async() + return RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, permission: List[str]) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(permission=permission) + return RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(permission=permission) + instance = RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, permission: List[str]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(permission=permission) + return RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(permission=permission) + instance = RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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] + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + return RoleInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def create_with_http_info( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Create the RoleInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + return RoleInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Asynchronously create the RoleInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RoleInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RoleInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..55e16cd848 --- /dev/null +++ b/twilio/rest/conversations/v1/service/user/__init__.py @@ -0,0 +1,1437 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + 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 + """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the UserInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return success + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() + return UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + return UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + return UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + return UserInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the UserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + return UserInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the UserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..7a05c5fc73 --- /dev/null +++ b/twilio/rest/conversations/v1/service/user/user_conversation.py @@ -0,0 +1,1135 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserConversationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserConversationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserConversationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserConversationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserConversationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserConversationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserConversationInstance: + """ + Fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + payload, _, _ = self._fetch() + 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> UserConversationInstance: + """ + Asynchronous coroutine to fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + payload, _, _ = await self._fetch_async() + 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + 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_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserConversationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + instance = UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserConversationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + instance = UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserConversationInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserConversationInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserConversationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserConversationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserConversationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserConversationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserConversationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserConversationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..b149577147 --- /dev/null +++ b/twilio/rest/conversations/v1/user/__init__.py @@ -0,0 +1,1383 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + 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 + """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the UserInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return success + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + return UserInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + return UserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + return UserInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the UserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + return UserInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the UserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..c6dd85ac39 --- /dev/null +++ b/twilio/rest/conversations/v1/user/user_conversation.py @@ -0,0 +1,1105 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserConversationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserConversationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserConversationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserConversationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserConversationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserConversationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserConversationInstance: + """ + Fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + payload, _, _ = self._fetch() + return UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> UserConversationInstance: + """ + Asynchronous coroutine to fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + payload, _, _ = await self._fetch_async() + return UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + return UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserConversationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + instance = UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + return UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserConversationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + instance = UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserConversationInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserConversationInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserConversationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserConversationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserConversationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserConversationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserConversationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserConversationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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/conversations/v2/__init__.py b/twilio/rest/conversations/v2/__init__.py new file mode 100644 index 0000000000..fd904a0c7b --- /dev/null +++ b/twilio/rest/conversations/v2/__init__.py @@ -0,0 +1,104 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Conversation Orchestrator + Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + + NOTE: This 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.v2.action import ActionList +from twilio.rest.conversations.v2.communication import CommunicationList +from twilio.rest.conversations.v2.configuration import ConfigurationList +from twilio.rest.conversations.v2.conversation import ConversationList +from twilio.rest.conversations.v2.operation import OperationList +from twilio.rest.conversations.v2.participant import ParticipantList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Conversations + + :param domain: The Twilio.conversations domain + """ + super().__init__(domain, "v2") + self._configurations: Optional[ConfigurationList] = None + self._conversations: Optional[ConversationList] = None + self._operations: Optional[OperationList] = None + + def actions(self, conversation_id: str, action_id: str = None): + """ + Access the ActionList resource + + :param conversation_id: + + :param action_id: Optional instance ID to directly access ActionContext + :returns: ActionList instance if action_id is None, otherwise ActionContext + """ + list_instance = ActionList(self, conversation_id) + if action_id is not None: + return list_instance(action_id) + return list_instance + + def communications(self, conversation_sid: str, communication_id: str = None): + """ + Access the CommunicationList resource + + :param conversation_sid: + + :param communication_id: Optional instance ID to directly access CommunicationContext + :returns: CommunicationList instance if communication_id is None, otherwise CommunicationContext + """ + list_instance = CommunicationList(self, conversation_sid) + if communication_id is not None: + return list_instance(communication_id) + return list_instance + + @property + def configurations(self) -> ConfigurationList: + if self._configurations is None: + self._configurations = ConfigurationList(self) + return self._configurations + + @property + def conversations(self) -> ConversationList: + if self._conversations is None: + self._conversations = ConversationList(self) + return self._conversations + + @property + def operations(self) -> OperationList: + if self._operations is None: + self._operations = OperationList(self) + return self._operations + + def participants(self, conversation_sid: str, participant_id: str = None): + """ + Access the ParticipantList resource + + :param conversation_sid: + + :param participant_id: Optional instance ID to directly access ParticipantContext + :returns: ParticipantList instance if participant_id is None, otherwise ParticipantContext + """ + list_instance = ParticipantList(self, conversation_sid) + if participant_id is not None: + return list_instance(participant_id) + return list_instance + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v2/action.py b/twilio/rest/conversations/v2/action.py new file mode 100644 index 0000000000..b2a656f35a --- /dev/null +++ b/twilio/rest/conversations/v2/action.py @@ -0,0 +1,512 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Conversation Orchestrator + Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.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 ActionInstance(InstanceResource): + """ + :ivar id: Unique identifier for this Action. + :ivar type: The type of action. Accepted values: SEND_MESSAGE. + :ivar status: Current status of the Action. - PENDING: Action accepted, awaiting downstream confirmation - COMPLETED: Downstream backend confirmed the action - FAILED: Downstream backend reported a failure + :ivar conversation_id: The conversation this action belongs to. + :ivar related: Named identifiers from downstream. For SEND_MESSAGE: - messageSid: The downstream message SID (present when PENDING or COMPLETED) - communicationId: The Communication ID (present when COMPLETED) + :ivar created_at: Timestamp when the action was created. + :ivar updated_at: Timestamp when the action was last updated. + :ivar completed_at: Timestamp when the action reached a terminal status. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_id: str, + action_id: Optional[str] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.type: Optional[str] = payload.get("type") + self.status: Optional["ActionInstance.str"] = payload.get("status") + self.conversation_id: Optional[str] = payload.get("conversationId") + self.related: Optional[Dict[str, str]] = payload.get("related") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.completed_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("completedAt") + ) + + # Only set _solution if path params are provided (not None) + if conversation_id is not None or action_id is not None: + self._solution = { + "conversation_id": conversation_id, + "action_id": action_id, + } + + self._context: Optional[ActionContext] = None + + @property + def _proxy(self) -> "ActionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ActionContext for this ActionInstance + """ + if self._context is None: + self._context = ActionContext( + self._version, + conversation_id=self._solution["conversation_id"], + action_id=self._solution["action_id"], + ) + return self._context + + def fetch(self) -> "ActionInstance": + """ + Fetch the ActionInstance + + + :returns: The fetched ActionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ActionInstance": + """ + Asynchronous coroutine to fetch the ActionInstance + + + :returns: The fetched ActionInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ActionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ActionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 ActionContext(InstanceContext): + + def __init__(self, version: Version, conversation_id: str, action_id: str): + """ + Initialize the ActionContext + + :param version: Version that contains the resource + :param conversation_id: + :param action_id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_id": conversation_id, + "action_id": action_id, + } + self._uri = "/Conversations/{conversation_id}/Actions/{action_id}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ActionInstance: + """ + Fetch the ActionInstance + + + :returns: The fetched ActionInstance + """ + payload, _, _ = self._fetch() + return ActionInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + action_id=self._solution["action_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ActionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ActionInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + action_id=self._solution["action_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ActionInstance: + """ + Asynchronous coroutine to fetch the ActionInstance + + + :returns: The fetched ActionInstance + """ + payload, _, _ = await self._fetch_async() + return ActionInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + action_id=self._solution["action_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ActionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ActionInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + action_id=self._solution["action_id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 ActionList(ListResource): + + class ConversationsV2SendMessageContent(object): + """ + :ivar text: Plain text message body. + :ivar content_id: Content template ID (HX... format). When provided, the template is rendered with the variables map and sent to the recipient. + :ivar variables: Variables to substitute into the content template. + :ivar media_urls: URLs of media attachments to include with the message. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.text: Optional[str] = payload.get("text") + self.content_id: Optional[str] = payload.get("contentId") + self.variables: Optional[Dict[str, str]] = payload.get("variables") + self.media_urls: Optional[List[str]] = payload.get("mediaUrls") + + def to_dict(self): + return { + "text": self.text, + "contentId": self.content_id, + "variables": self.variables, + "mediaUrls": self.media_urls, + } + + class ConversationsV2SendMessageParticipant(object): + """ + :ivar participant_id: Participant ID to resolve address from. + :ivar address: Explicit address formatted according to channel type. + :ivar channel: Channel type for address resolution. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.participant_id: Optional[str] = payload.get("participantId") + self.address: Optional[str] = payload.get("address") + self.channel: Optional["ActionInstance.str"] = payload.get("channel") + + def to_dict(self): + return { + "participantId": self.participant_id, + "address": self.address, + "channel": self.channel, + } + + class ConversationsV2SendMessagePayload(object): + """ + :ivar _from: + :ivar to: The recipients of this action. + :ivar content: + :ivar channel_settings: Channel-specific parameters forwarded as-is to the downstream sending service. Allows passing backend-specific fields without requiring API changes. + """ + + def __init__(self, payload: Dict[str, Any]): + + self._from: Optional[ActionList.ConversationsV2SendMessageParticipant] = ( + payload.get("from") + ) + self.to: Optional[ + List[ActionList.ConversationsV2SendMessageParticipant] + ] = payload.get("to") + self.content: Optional[ActionList.ConversationsV2SendMessageContent] = ( + payload.get("content") + ) + self.channel_settings: Optional[Dict[str, object]] = payload.get( + "channelSettings" + ) + + def to_dict(self): + return { + "from": self._from.to_dict() if self._from is not None else None, + "to": [to.to_dict() for to in self.to] if self.to is not None else None, + "content": self.content.to_dict() if self.content is not None else None, + "channelSettings": self.channel_settings, + } + + class CreateConversationActionRequest(object): + """ + :ivar type: Action type discriminator. Accepted values: SEND_MESSAGE. + :ivar payload: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional[str] = payload.get("type") + self.payload: Optional[ActionList.ConversationsV2SendMessagePayload] = ( + payload.get("payload") + ) + + def to_dict(self): + return { + "type": self.type, + "payload": self.payload.to_dict() if self.payload is not None else None, + } + + def __init__(self, version: Version, conversation_id: str): + """ + Initialize the ActionList + + :param version: Version that contains the resource + :param conversation_id: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_id": conversation_id, + } + self._uri = "/Conversations/{conversation_id}/Actions".format(**self._solution) + + def _create( + self, create_conversation_action_request: CreateConversationActionRequest + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_conversation_action_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_conversation_action_request: CreateConversationActionRequest + ) -> ActionInstance: + """ + Create the ActionInstance + + :param create_conversation_action_request: The action to perform. + + :returns: The created ActionInstance + """ + payload, _, _ = self._create( + create_conversation_action_request=create_conversation_action_request + ) + return ActionInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + + def create_with_http_info( + self, create_conversation_action_request: CreateConversationActionRequest + ) -> ApiResponse: + """ + Create the ActionInstance and return response metadata + + :param create_conversation_action_request: The action to perform. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_conversation_action_request=create_conversation_action_request + ) + instance = ActionInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_conversation_action_request: CreateConversationActionRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_conversation_action_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_conversation_action_request: CreateConversationActionRequest + ) -> ActionInstance: + """ + Asynchronously create the ActionInstance + + :param create_conversation_action_request: The action to perform. + + :returns: The created ActionInstance + """ + payload, _, _ = await self._create_async( + create_conversation_action_request=create_conversation_action_request + ) + return ActionInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + + async def create_with_http_info_async( + self, create_conversation_action_request: CreateConversationActionRequest + ) -> ApiResponse: + """ + Asynchronously create the ActionInstance and return response metadata + + :param create_conversation_action_request: The action to perform. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_conversation_action_request=create_conversation_action_request + ) + instance = ActionInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def get(self, action_id: str) -> ActionContext: + """ + Constructs a ActionContext + + :param action_id: + """ + return ActionContext( + self._version, + conversation_id=self._solution["conversation_id"], + action_id=action_id, + ) + + def __call__(self, action_id: str) -> ActionContext: + """ + Constructs a ActionContext + + :param action_id: + """ + return ActionContext( + self._version, + conversation_id=self._solution["conversation_id"], + action_id=action_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v2/communication.py b/twilio/rest/conversations/v2/communication.py new file mode 100644 index 0000000000..c8875a2756 --- /dev/null +++ b/twilio/rest/conversations/v2/communication.py @@ -0,0 +1,1037 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Conversation Orchestrator + Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class CommunicationInstance(InstanceResource): + """ + :ivar id: Communication ID. + :ivar conversation_id: Conversation ID. + :ivar account_id: Account ID. + :ivar author: + :ivar content: + :ivar channel_id: Channel-specific reference ID. + :ivar resource_id: External resource identifier for this Communication (e.g. MessageSid for SMS/RCS/WhatsApp, TranscriptionSid + MessageIndex for Voice). When set, used for Communication deduplication/uniqueness within a Conversation. + :ivar recipients: Communication recipients. + :ivar created_at: Timestamp when this Communication was created. + :ivar updated_at: Timestamp when this Communication was last updated. + :ivar occurred_at: ISO 8601 timestamp when the communication occurred. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.conversation_id: Optional[str] = payload.get("conversationId") + self.account_id: Optional[str] = payload.get("accountId") + self.author: Optional[str] = payload.get("author") + self.content: Optional[str] = payload.get("content") + self.channel_id: Optional[str] = payload.get("channelId") + self.resource_id: Optional[str] = payload.get("resourceId") + self.recipients: Optional[List[str]] = payload.get("recipients") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.occurred_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("occurredAt") + ) + + # Only set _solution if path params are provided (not None) + if conversation_sid is not None or sid is not None: + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + + self._context: Optional[CommunicationContext] = None + + @property + def _proxy(self) -> "CommunicationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CommunicationContext for this CommunicationInstance + """ + if self._context is None: + self._context = CommunicationContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "CommunicationInstance": + """ + Fetch the CommunicationInstance + + + :returns: The fetched CommunicationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CommunicationInstance": + """ + Asynchronous coroutine to fetch the CommunicationInstance + + + :returns: The fetched CommunicationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CommunicationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CommunicationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 CommunicationContext(InstanceContext): + + def __init__(self, version: Version, conversation_sid: str, sid: str): + """ + Initialize the CommunicationContext + + :param version: Version that contains the resource + :param conversation_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Communications/{sid}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CommunicationInstance: + """ + Fetch the CommunicationInstance + + + :returns: The fetched CommunicationInstance + """ + payload, _, _ = self._fetch() + return CommunicationInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CommunicationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CommunicationInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CommunicationInstance: + """ + Asynchronous coroutine to fetch the CommunicationInstance + + + :returns: The fetched CommunicationInstance + """ + payload, _, _ = await self._fetch_async() + return CommunicationInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CommunicationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CommunicationInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 CommunicationPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> CommunicationInstance: + """ + Build an instance of CommunicationInstance + + :param payload: Payload response from the API + """ + + return CommunicationInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CommunicationList(ListResource): + + class ContentTranscriptionTranscription(object): + """ + :ivar channel: + :ivar confidence: + :ivar engine: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channel: Optional[int] = payload.get("channel") + self.confidence: Optional[float] = payload.get("confidence") + self.engine: Optional[str] = payload.get("engine") + + def to_dict(self): + return { + "channel": self.channel, + "confidence": self.confidence, + "engine": self.engine, + } + + class ConversationsV2ContentTranscriptionTranscription(object): + """ + :ivar channel: Audio channel identifier (0 for inbound, 1 for outbound). + :ivar confidence: Overall confidence score for the transcription (0.0-1.0). + :ivar engine: Transcription engine used. + :ivar words: Word-level transcription data with timing information. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channel: Optional[int] = payload.get("channel") + self.confidence: Optional[float] = payload.get("confidence") + self.engine: Optional[str] = payload.get("engine") + self.words: Optional[ + List[ConversationsV2ContentTranscriptionTranscriptionWords] + ] = payload.get("words") + + def to_dict(self): + return { + "channel": self.channel, + "confidence": self.confidence, + "engine": self.engine, + "words": ( + [words.to_dict() for words in self.words] + if self.words is not None + else None + ), + } + + class ConversationsV2ContentTranscriptionTranscriptionWords(object): + """ + :ivar text: The transcribed word. + :ivar start_time: Start timestamp of this word. + :ivar end_time: End timestamp of this word. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.text: Optional[str] = payload.get("text") + self.start_time: Optional[datetime] = payload.get("startTime") + self.end_time: Optional[datetime] = payload.get("endTime") + + def to_dict(self): + return { + "text": self.text, + "startTime": self.start_time, + "endTime": self.end_time, + } + + class CreateCommunicationInConversationRequest(object): + """ + :ivar author: + :ivar content: + :ivar channel_id: + :ivar recipients: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.author: Optional[ + CommunicationList.CreateCommunicationInConversationRequestAuthor + ] = payload.get("author") + self.content: Optional[ + CommunicationList.CreateCommunicationInConversationRequestContent + ] = payload.get("content") + self.channel_id: Optional[str] = payload.get("channelId") + self.recipients: Optional[ + List[CommunicationList.CreateCommunicationInConversationRequestAuthor] + ] = payload.get("recipients") + + def to_dict(self): + return { + "author": self.author.to_dict() if self.author is not None else None, + "content": self.content.to_dict() if self.content is not None else None, + "channelId": self.channel_id, + "recipients": ( + [recipients.to_dict() for recipients in self.recipients] + if self.recipients is not None + else None + ), + } + + class CreateCommunicationInConversationRequestAuthor(object): + """ + :ivar address: + :ivar channel: + :ivar participant_id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.address: Optional[str] = payload.get("address") + self.channel: Optional["CommunicationInstance.str"] = payload.get("channel") + self.participant_id: Optional[str] = payload.get("participantId") + + def to_dict(self): + return { + "address": self.address, + "channel": self.channel, + "participantId": self.participant_id, + } + + class CreateCommunicationInConversationRequestContent(object): + """ + :ivar type: + :ivar text: + :ivar transcription: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["CommunicationInstance.str"] = payload.get("type") + self.text: Optional[str] = payload.get("text") + self.transcription: Optional[ + CommunicationList.ContentTranscriptionTranscription + ] = payload.get("transcription") + + def to_dict(self): + return { + "type": self.type, + "text": self.text, + "transcription": ( + self.transcription.to_dict() + if self.transcription is not None + else None + ), + } + + def __init__(self, version: Version, conversation_sid: str): + """ + Initialize the CommunicationList + + :param version: Version that contains the resource + :param conversation_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + } + self._uri = "/Conversations/{conversation_sid}/Communications".format( + **self._solution + ) + + def _create( + self, + create_communication_in_conversation_request: Union[ + CreateCommunicationInConversationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_communication_in_conversation_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + create_communication_in_conversation_request: Union[ + CreateCommunicationInConversationRequest, object + ] = values.unset, + ) -> CommunicationInstance: + """ + Create the CommunicationInstance + + :param create_communication_in_conversation_request: + + :returns: The created CommunicationInstance + """ + payload, _, _ = self._create( + create_communication_in_conversation_request=create_communication_in_conversation_request + ) + return CommunicationInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def create_with_http_info( + self, + create_communication_in_conversation_request: Union[ + CreateCommunicationInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the CommunicationInstance and return response metadata + + :param create_communication_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_communication_in_conversation_request=create_communication_in_conversation_request + ) + instance = CommunicationInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + create_communication_in_conversation_request: Union[ + CreateCommunicationInConversationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_communication_in_conversation_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + create_communication_in_conversation_request: Union[ + CreateCommunicationInConversationRequest, object + ] = values.unset, + ) -> CommunicationInstance: + """ + Asynchronously create the CommunicationInstance + + :param create_communication_in_conversation_request: + + :returns: The created CommunicationInstance + """ + payload, _, _ = await self._create_async( + create_communication_in_conversation_request=create_communication_in_conversation_request + ) + return CommunicationInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + async def create_with_http_info_async( + self, + create_communication_in_conversation_request: Union[ + CreateCommunicationInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CommunicationInstance and return response metadata + + :param create_communication_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_communication_in_conversation_request=create_communication_in_conversation_request + ) + instance = CommunicationInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CommunicationInstance]: + """ + Streams CommunicationInstance records from the API as a generator stream. + This operation lazily loads records 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_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.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_id=channel_id, page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CommunicationInstance]: + """ + Asynchronously streams CommunicationInstance records from the API as a generator stream. + This operation lazily loads records 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_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(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_id=channel_id, page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CommunicationInstance and returns headers from first page + + + :param str channel_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + channel_id=channel_id, page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CommunicationInstance and returns headers from first page + + + :param str channel_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + channel_id=channel_id, page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CommunicationInstance]: + """ + Lists CommunicationInstance 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_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + 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_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CommunicationInstance]: + """ + Asynchronously lists CommunicationInstance 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_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CommunicationInstance and returns headers from first page + + + :param str channel_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + channel_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CommunicationInstance and returns headers from first page + + + :param str channel_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + channel_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + channel_id: Union[str, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> CommunicationPage: + """ + Retrieve a single page of CommunicationInstance records from the API. + Request is executed immediately + + :param channel_id: Resource identifier to filter communications + :param page_size: Maximum number of items to return + :param page_token: Page token for pagination + :returns: Page of CommunicationInstance + """ + data = values.of( + { + "channelId": channel_id, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CommunicationPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + channel_id: Union[str, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> CommunicationPage: + """ + Asynchronously retrieve a single page of CommunicationInstance records from the API. + Request is executed immediately + + :param channel_id: Resource identifier to filter communications + :param page_size: Maximum number of items to return + :param page_token: Page token for pagination + :returns: Page of CommunicationInstance + """ + data = values.of( + { + "channelId": channel_id, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CommunicationPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + channel_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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param channel_id: Resource identifier to filter communications + :param page_token: Page token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CommunicationPage, status code, and headers + """ + data = values.of( + { + "channelId": channel_id, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CommunicationPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + channel_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param channel_id: Resource identifier to filter communications + :param page_token: Page token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CommunicationPage, status code, and headers + """ + data = values.of( + { + "channelId": channel_id, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CommunicationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> CommunicationPage: + """ + Retrieve a specific page of CommunicationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CommunicationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CommunicationPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> CommunicationPage: + """ + Asynchronously retrieve a specific page of CommunicationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CommunicationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CommunicationPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> CommunicationContext: + """ + Constructs a CommunicationContext + + :param sid: + """ + return CommunicationContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __call__(self, sid: str) -> CommunicationContext: + """ + Constructs a CommunicationContext + + :param sid: + """ + return CommunicationContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v2/configuration.py b/twilio/rest/conversations/v2/configuration.py new file mode 100644 index 0000000000..f2939d1359 --- /dev/null +++ b/twilio/rest/conversations/v2/configuration.py @@ -0,0 +1,1655 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Conversation Orchestrator + Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ConfigurationInstance(InstanceResource): + """ + :ivar id: Configuration ID. + :ivar display_name: A human-readable name for the configuration. Limited to 32 characters. + :ivar description: Human-readable description for the Configuration. Allows spaces and special characters, typically limited to a paragraph of text. This serves as a descriptive field rather than just a name. + :ivar conversation_grouping_type: Type of Conversation grouping strategy: - `GROUP_BY_PROFILE`: Groups Communications by resolved Profile from the Memory Store. A Profile is looked up or created for `CUSTOMER` Participant types. All Communications from the same Profile are in the same Conversation, regardless of address or channel. - `GROUP_BY_PARTICIPANT_ADDRESSES`: Groups Communications by Participant addresses across all channels. A customer using +18005550100 will be in the same Conversation whether they contact by SMS, WhatsApp, or RCS. - `GROUP_BY_PARTICIPANT_ADDRESSES_AND_CHANNEL_TYPE`: Groups Communications by both Participant addresses AND channel. A customer using +18005550100 by SMS will be in a different Conversation than the same customer by Voice. + :ivar memory_store_id: Memory Store ID for Profile resolution. + :ivar channel_settings: Channel-specific configuration settings by channel type. Keys should be valid channel types (`VOICE`, `SMS`, `RCS`, `WHATSAPP`, `CHAT`). + :ivar status_callbacks: List of default webhook configurations applied to Conversations under this Configuration. + :ivar intelligence_configuration_ids: A list of Conversational Intelligence configuration IDs. + :ivar memory_extraction_enabled: Whether memory extraction is enabled for conversations under this configuration. Defaults to false. + :ivar conversations_v1_bridge: + :ivar created_at: Timestamp when this Configuration was created. + :ivar updated_at: Timestamp when this Configuration was last updated. + :ivar version: Version number used for optimistic locking. + :ivar status_url: URL to poll for operation status. + :ivar related: Named resource identifiers associated with this operation. Keys depend on the operation type: - config-create, config-update, config-delete: configurationId - conversation-delete: conversationId + """ + + def __init__( + self, version: Version, payload: ResponseResource, sid: Optional[str] = None + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.conversation_grouping_type: Optional["ConfigurationInstance.str"] = ( + payload.get("conversationGroupingType") + ) + self.memory_store_id: Optional[str] = payload.get("memoryStoreId") + self.channel_settings: Optional[Dict[str, ConversationsV2ChannelSetting]] = ( + payload.get("channelSettings") + ) + self.status_callbacks: Optional[List[ConversationsV2StatusCallbackConfig]] = ( + payload.get("statusCallbacks") + ) + self.intelligence_configuration_ids: Optional[List[str]] = payload.get( + "intelligenceConfigurationIds" + ) + self.memory_extraction_enabled: Optional[bool] = payload.get( + "memoryExtractionEnabled" + ) + self.conversations_v1_bridge: Optional[ConversationsV2ConversationsV1Bridge] = ( + payload.get("conversationsV1Bridge") + ) + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.version: Optional[int] = payload.get("version") + self.status_url: Optional[str] = payload.get("statusUrl") + self.related: Optional[Dict[str, str]] = payload.get("related") + + # Only set _solution if path params are provided (not None) + if sid is not None: + self._solution = { + "sid": 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, + sid=self._solution["sid"], + ) + return self._context + + def delete(self, idempotency_key: Union[str, object] = values.unset) -> bool: + """ + Deletes the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + idempotency_key=idempotency_key, + ) + + async def delete_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + idempotency_key=idempotency_key, + ) + + def delete_with_http_info( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the ConfigurationInstance with HTTP info + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + idempotency_key=idempotency_key, + ) + + async def delete_with_http_info_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConfigurationInstance with HTTP info + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + idempotency_key=idempotency_key, + ) + + 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> "ConfigurationInstance": + """ + Update the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: The updated ConfigurationInstance + """ + return self._proxy.update( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_request, + ) + + async def update_async( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> "ConfigurationInstance": + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: The updated ConfigurationInstance + """ + return await self._proxy.update_async( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_request, + ) + + def update_with_http_info( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ConfigurationInstance with HTTP info + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_request, + ) + + async def update_with_http_info_async( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance with HTTP info + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_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 ConfigurationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ConfigurationContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/ControlPlane/Configurations/{sid}".format(**self._solution) + + def _delete(self, idempotency_key: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Idempotency-Key": idempotency_key, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self, idempotency_key: Union[str, object] = values.unset) -> bool: + """ + Deletes the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete(idempotency_key=idempotency_key) + return success + + def delete_with_http_info( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the ConfigurationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(idempotency_key=idempotency_key) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Idempotency-Key": idempotency_key, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async(idempotency_key=idempotency_key) + return success + + async def delete_with_http_info_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConfigurationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + idempotency_key=idempotency_key + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConfigurationInstance: + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = self._fetch() + return ConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = await self._fetch_async() + return ConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_configuration_request.to_dict() + + headers = values.of({}) + + if not ( + idempotency_key is values.unset + or (isinstance(idempotency_key, str) and not idempotency_key) + ): + headers["Idempotency-Key"] = idempotency_key + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> ConfigurationInstance: + """ + Update the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = self._update( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_request, + ) + return ConfigurationInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ConfigurationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_request, + ) + instance = ConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_configuration_request.to_dict() + + headers = values.of({}) + + if not ( + idempotency_key is values.unset + or (isinstance(idempotency_key, str) and not idempotency_key) + ): + headers["Idempotency-Key"] = idempotency_key + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = await self._update_async( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_request, + ) + return ConfigurationInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_request, + ) + instance = ConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 ConfigurationPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ConfigurationInstance: + """ + Build an instance of ConfigurationInstance + + :param payload: Payload response from the API + """ + + return ConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConfigurationList(ListResource): + + class ConversationsV2CaptureRule(object): + """ + :ivar _from: The from address. Use `*` for wildcard to match any from address. + :ivar to: The to address. Use `*` for wildcard to match any to address. + :ivar metadata: Additional matching criteria for the capture rule. For voice calls, can include `callType` (`PSTN`, `SIP`, and similar). + """ + + def __init__(self, payload: Dict[str, Any]): + + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.metadata: Optional[Dict[str, str]] = payload.get("metadata") + + def to_dict(self): + return { + "from": self._from, + "to": self.to, + "metadata": self.metadata, + } + + class ConversationsV2ChannelSetting(object): + """ + :ivar status_timeouts: + :ivar capture_rules: Array of capture rules with from/to addresses and optional metadata. Use `*` for wildcard matching in either direction. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.status_timeouts: Optional[ConversationsV2StatusTimeouts] = payload.get( + "statusTimeouts" + ) + self.capture_rules: Optional[List[ConversationsV2CaptureRule]] = ( + payload.get("captureRules") + ) + + def to_dict(self): + return { + "statusTimeouts": ( + self.status_timeouts.to_dict() + if self.status_timeouts is not None + else None + ), + "captureRules": ( + [capture_rules.to_dict() for capture_rules in self.capture_rules] + if self.capture_rules is not None + else None + ), + } + + class ConversationsV2ConversationsV1Bridge(object): + """ + :ivar service_id: The Conversations V1 Service SID (IS prefix). One configuration per V1 Service SID. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.service_id: Optional[str] = payload.get("serviceId") + + def to_dict(self): + return { + "serviceId": self.service_id, + } + + class ConversationsV2StatusCallbackConfig(object): + """ + :ivar url: Destination URL for webhooks. + :ivar method: HTTP method used to invoke the webhook URL. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional[str] = payload.get("method") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + } + + class ConversationsV2StatusTimeouts(object): + """ + :ivar inactive: Inactivity timeout in minutes. + :ivar closed: Close timeout in minutes. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.inactive: Optional[int] = payload.get("inactive") + self.closed: Optional[int] = payload.get("closed") + + def to_dict(self): + return { + "inactive": self.inactive, + "closed": self.closed, + } + + class CreateConfigurationRequest(object): + """ + :ivar display_name: A human-readable name for the configuration. Limited to 32 characters. + :ivar description: Human-readable description for the configuration. + :ivar conversation_grouping_type: The strategy Conversation Orchestrator uses to assign communications to conversations. + :ivar memory_store_id: The memory store ID that Conversation Orchestrator uses for profile resolution. + :ivar channel_settings: + :ivar status_callbacks: A list of webhook configurations. + :ivar intelligence_configuration_ids: A list of Conversational Intelligence configuration IDs. + :ivar memory_extraction_enabled: Whether memory extraction is enabled for conversations under this configuration. Defaults to false. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.conversation_grouping_type: Optional["ConfigurationInstance.str"] = ( + payload.get("conversationGroupingType") + ) + self.memory_store_id: Optional[str] = payload.get("memoryStoreId") + self.channel_settings: Optional[ + Dict[str, CreateConfigurationRequestChannelSettingsValue] + ] = payload.get("channelSettings") + self.status_callbacks: Optional[ + List[ConfigurationList.CreateConfigurationRequestStatusCallbacks] + ] = payload.get("statusCallbacks") + self.intelligence_configuration_ids: Optional[List[str]] = payload.get( + "intelligenceConfigurationIds" + ) + self.memory_extraction_enabled: Optional[bool] = payload.get( + "memoryExtractionEnabled" + ) + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "conversationGroupingType": self.conversation_grouping_type, + "memoryStoreId": self.memory_store_id, + "channelSettings": ( + {k: v.to_dict() for k, v in self.channel_settings.items()} + if self.channel_settings is not None + else None + ), + "statusCallbacks": ( + [ + status_callbacks.to_dict() + for status_callbacks in self.status_callbacks + ] + if self.status_callbacks is not None + else None + ), + "intelligenceConfigurationIds": self.intelligence_configuration_ids, + "memoryExtractionEnabled": self.memory_extraction_enabled, + } + + class CreateConfigurationRequestChannelSettingsValue(object): + """ + :ivar status_timeouts: + :ivar capture_rules: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.status_timeouts: Optional[ + CreateConfigurationRequestChannelSettingsValueStatusTimeouts + ] = payload.get("statusTimeouts") + self.capture_rules: Optional[ + List[CreateConfigurationRequestChannelSettingsValueCaptureRules] + ] = payload.get("captureRules") + + def to_dict(self): + return { + "statusTimeouts": ( + self.status_timeouts.to_dict() + if self.status_timeouts is not None + else None + ), + "captureRules": ( + [capture_rules.to_dict() for capture_rules in self.capture_rules] + if self.capture_rules is not None + else None + ), + } + + class CreateConfigurationRequestChannelSettingsValueCaptureRules(object): + """ + :ivar _from: The from address. Use '*' for wildcard. + :ivar to: The to address. Use '*' for wildcard. + :ivar metadata: + """ + + def __init__(self, payload: Dict[str, Any]): + + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.metadata: Optional[Dict[str, str]] = payload.get("metadata") + + def to_dict(self): + return { + "from": self._from, + "to": self.to, + "metadata": self.metadata, + } + + class CreateConfigurationRequestChannelSettingsValueStatusTimeouts(object): + """ + :ivar inactive: The inactivity timeout in minutes. For more information, see [Conversation lifecycle](/docs/platform/conversations/concepts/lifecycle). + :ivar closed: The close timeout in minutes. For more information, see [Conversation lifecycle](/docs/platform/conversations/concepts/lifecycle). + """ + + def __init__(self, payload: Dict[str, Any]): + + self.inactive: Optional[int] = payload.get("inactive") + self.closed: Optional[int] = payload.get("closed") + + def to_dict(self): + return { + "inactive": self.inactive, + "closed": self.closed, + } + + class CreateConfigurationRequestStatusCallbacks(object): + """ + :ivar url: The destination URL for webhooks. + :ivar method: The HTTP method used to invoke the webhook URL. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional["ConfigurationInstance.str"] = payload.get("method") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + } + + class UpdateConfigurationRequest(object): + """ + :ivar display_name: A human-readable name for the configuration. Limited to 32 characters. + :ivar description: Human-readable description for the configuration. + :ivar conversation_grouping_type: The strategy Conversation Orchestrator uses to assign communications to conversations. + :ivar memory_store_id: The Memory Store ID for profile resolution. + :ivar channel_settings: + :ivar status_callbacks: + :ivar intelligence_configuration_ids: A list of Conversational Intelligence configuration IDs. + :ivar memory_extraction_enabled: Whether memory extraction is enabled for conversations under this configuration. Defaults to false. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.conversation_grouping_type: Optional["ConfigurationInstance.str"] = ( + payload.get("conversationGroupingType") + ) + self.memory_store_id: Optional[str] = payload.get("memoryStoreId") + self.channel_settings: Optional[ + Dict[str, UpdateConfigurationRequestChannelSettingsValue] + ] = payload.get("channelSettings") + self.status_callbacks: Optional[ + List[ConfigurationList.UpdateConfigurationRequestStatusCallbacks] + ] = payload.get("statusCallbacks") + self.intelligence_configuration_ids: Optional[List[str]] = payload.get( + "intelligenceConfigurationIds" + ) + self.memory_extraction_enabled: Optional[bool] = payload.get( + "memoryExtractionEnabled" + ) + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "conversationGroupingType": self.conversation_grouping_type, + "memoryStoreId": self.memory_store_id, + "channelSettings": ( + {k: v.to_dict() for k, v in self.channel_settings.items()} + if self.channel_settings is not None + else None + ), + "statusCallbacks": ( + [ + status_callbacks.to_dict() + for status_callbacks in self.status_callbacks + ] + if self.status_callbacks is not None + else None + ), + "intelligenceConfigurationIds": self.intelligence_configuration_ids, + "memoryExtractionEnabled": self.memory_extraction_enabled, + } + + class UpdateConfigurationRequestChannelSettingsValue(object): + """ + :ivar status_timeouts: + :ivar capture_rules: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.status_timeouts: Optional[ + UpdateConfigurationRequestChannelSettingsValueStatusTimeouts + ] = payload.get("statusTimeouts") + self.capture_rules: Optional[ + List[UpdateConfigurationRequestChannelSettingsValueCaptureRules] + ] = payload.get("captureRules") + + def to_dict(self): + return { + "statusTimeouts": ( + self.status_timeouts.to_dict() + if self.status_timeouts is not None + else None + ), + "captureRules": ( + [capture_rules.to_dict() for capture_rules in self.capture_rules] + if self.capture_rules is not None + else None + ), + } + + class UpdateConfigurationRequestChannelSettingsValueCaptureRules(object): + """ + :ivar _from: + :ivar to: + :ivar metadata: + """ + + def __init__(self, payload: Dict[str, Any]): + + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.metadata: Optional[Dict[str, str]] = payload.get("metadata") + + def to_dict(self): + return { + "from": self._from, + "to": self.to, + "metadata": self.metadata, + } + + class UpdateConfigurationRequestChannelSettingsValueStatusTimeouts(object): + """ + :ivar inactive: + :ivar closed: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.inactive: Optional[int] = payload.get("inactive") + self.closed: Optional[int] = payload.get("closed") + + def to_dict(self): + return { + "inactive": self.inactive, + "closed": self.closed, + } + + class UpdateConfigurationRequestStatusCallbacks(object): + """ + :ivar url: + :ivar method: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional["ConfigurationInstance.str"] = payload.get("method") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + } + + def __init__(self, version: Version): + """ + Initialize the ConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ControlPlane/Configurations" + + def _create( + self, + idempotency_key: Union[str, object] = values.unset, + create_configuration_request: Union[ + CreateConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_configuration_request.to_dict() + + headers = values.of( + { + "Idempotency-Key": idempotency_key, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + idempotency_key: Union[str, object] = values.unset, + create_configuration_request: Union[ + CreateConfigurationRequest, object + ] = values.unset, + ) -> ConfigurationInstance: + """ + Create the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param create_configuration_request: The configuration to create + + :returns: The created ConfigurationInstance + """ + payload, _, _ = self._create( + idempotency_key=idempotency_key, + create_configuration_request=create_configuration_request, + ) + return ConfigurationInstance(self._version, payload) + + def create_with_http_info( + self, + idempotency_key: Union[str, object] = values.unset, + create_configuration_request: Union[ + CreateConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the ConfigurationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param create_configuration_request: The configuration to create + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + idempotency_key=idempotency_key, + create_configuration_request=create_configuration_request, + ) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + idempotency_key: Union[str, object] = values.unset, + create_configuration_request: Union[ + CreateConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_configuration_request.to_dict() + + headers = values.of( + { + "Idempotency-Key": idempotency_key, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + idempotency_key: Union[str, object] = values.unset, + create_configuration_request: Union[ + CreateConfigurationRequest, object + ] = values.unset, + ) -> ConfigurationInstance: + """ + Asynchronously create the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param create_configuration_request: The configuration to create + + :returns: The created ConfigurationInstance + """ + payload, _, _ = await self._create_async( + idempotency_key=idempotency_key, + create_configuration_request=create_configuration_request, + ) + return ConfigurationInstance(self._version, payload) + + async def create_with_http_info_async( + self, + idempotency_key: Union[str, object] = values.unset, + create_configuration_request: Union[ + CreateConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ConfigurationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param create_configuration_request: The configuration to create + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + idempotency_key=idempotency_key, + create_configuration_request=create_configuration_request, + ) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConfigurationInstance]: + """ + Streams ConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store 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( + page_token=page_token, + memory_store_id=memory_store_id, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConfigurationInstance]: + """ + Asynchronously streams ConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store 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( + page_token=page_token, + memory_store_id=memory_store_id, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConfigurationInstance and returns headers from first page + + + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, + memory_store_id=memory_store_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConfigurationInstance and returns headers from first page + + + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, + memory_store_id=memory_store_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConfigurationInstance]: + """ + Lists ConfigurationInstance 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: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store 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( + page_token=page_token, + memory_store_id=memory_store_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConfigurationInstance]: + """ + Asynchronously lists ConfigurationInstance 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: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store 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( + page_token=page_token, + memory_store_id=memory_store_id, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConfigurationInstance and returns headers from first page + + + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + memory_store_id=memory_store_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConfigurationInstance and returns headers from first page + + + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + memory_store_id=memory_store_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + ) -> ConfigurationPage: + """ + Retrieve a single page of ConfigurationInstance records from the API. + Request is executed immediately + + :param page_size: Maximum number of items to return in a single response + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :param memory_store_id: Filter configurations by Memory Store ID + :returns: Page of ConfigurationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "memoryStoreId": memory_store_id, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConfigurationPage(self._version, response, uri=self._uri, params=data) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + ) -> ConfigurationPage: + """ + Asynchronously retrieve a single page of ConfigurationInstance records from the API. + Request is executed immediately + + :param page_size: Maximum number of items to return in a single response + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :param memory_store_id: Filter configurations by Memory Store ID + :returns: Page of ConfigurationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "memoryStoreId": memory_store_id, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConfigurationPage(self._version, response, uri=self._uri, params=data) + + def page_with_http_info( + self, + memory_store_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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :param memory_store_id: Filter configurations by Memory Store 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: ApiResponse with ConfigurationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "memoryStoreId": memory_store_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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConfigurationPage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + memory_store_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :param memory_store_id: Filter configurations by Memory Store 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: ApiResponse with ConfigurationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "memoryStoreId": memory_store_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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ConfigurationPage: + """ + Retrieve a specific page of ConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConfigurationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConfigurationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConfigurationPage: + """ + Asynchronously retrieve a specific page of ConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConfigurationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConfigurationPage(self._version, response) + + def get(self, sid: str) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + :param sid: + """ + return ConfigurationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + :param sid: + """ + return ConfigurationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v2/conversation.py b/twilio/rest/conversations/v2/conversation.py new file mode 100644 index 0000000000..62a48c115b --- /dev/null +++ b/twilio/rest/conversations/v2/conversation.py @@ -0,0 +1,1613 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Conversation Orchestrator + Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ConversationInstance(InstanceResource): + """ + :ivar id: Conversation ID. + :ivar account_id: Account ID. + :ivar configuration_id: Configuration ID. + :ivar status: Conversation status. + :ivar name: Conversation name. + :ivar created_at: Timestamp when this Conversation was created. + :ivar updated_at: Timestamp when this Conversation was last updated. + :ivar configuration: + :ivar participants: Participants in this Conversation. + :ivar status_url: URL to poll for operation status. + :ivar related: Named resource identifiers associated with this operation. Keys depend on the operation type: - config-create, config-update, config-delete: configurationId - conversation-delete: conversationId + """ + + def __init__( + self, version: Version, payload: ResponseResource, sid: Optional[str] = None + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.account_id: Optional[str] = payload.get("accountId") + self.configuration_id: Optional[str] = payload.get("configurationId") + self.status: Optional["ConversationInstance.str"] = payload.get("status") + self.name: Optional[str] = payload.get("name") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.configuration: Optional[str] = payload.get("configuration") + self.participants: Optional[List[str]] = payload.get("participants") + self.status_url: Optional[str] = payload.get("statusUrl") + self.related: Optional[Dict[str, str]] = payload.get("related") + + # Only set _solution if path params are provided (not None) + if sid is not None: + self._solution = { + "sid": sid, + } + + self._context: Optional[ConversationContext] = None + + @property + def _proxy(self) -> "ConversationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConversationContext for this ConversationInstance + """ + if self._context is None: + self._context = ConversationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self, idempotency_key: Union[str, object] = values.unset) -> bool: + """ + Deletes the ConversationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + idempotency_key=idempotency_key, + ) + + async def delete_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the ConversationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + idempotency_key=idempotency_key, + ) + + def delete_with_http_info( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the ConversationInstance with HTTP info + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + idempotency_key=idempotency_key, + ) + + async def delete_with_http_info_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationInstance with HTTP info + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + idempotency_key=idempotency_key, + ) + + 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def patch( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> "ConversationInstance": + """ + Patch the ConversationInstance + + :param patch_conversation_by_id_request: The conversation fields to update + + :returns: The patched ConversationInstance + """ + return self._proxy.patch( + patch_conversation_by_id_request=patch_conversation_by_id_request, + ) + + async def patch_async( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> "ConversationInstance": + """ + Asynchronous coroutine to patch the ConversationInstance + + :param patch_conversation_by_id_request: The conversation fields to update + + :returns: The patched ConversationInstance + """ + return await self._proxy.patch_async( + patch_conversation_by_id_request=patch_conversation_by_id_request, + ) + + def update( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> "ConversationInstance": + """ + Update the ConversationInstance + + :param update_conversation_by_id_request: The conversation to update + + :returns: The updated ConversationInstance + """ + return self._proxy.update( + update_conversation_by_id_request=update_conversation_by_id_request, + ) + + async def update_async( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> "ConversationInstance": + """ + Asynchronous coroutine to update the ConversationInstance + + :param update_conversation_by_id_request: The conversation to update + + :returns: The updated ConversationInstance + """ + return await self._proxy.update_async( + update_conversation_by_id_request=update_conversation_by_id_request, + ) + + def update_with_http_info( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ConversationInstance with HTTP info + + :param update_conversation_by_id_request: The conversation to update + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + update_conversation_by_id_request=update_conversation_by_id_request, + ) + + async def update_with_http_info_async( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConversationInstance with HTTP info + + :param update_conversation_by_id_request: The conversation to update + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + update_conversation_by_id_request=update_conversation_by_id_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 ConversationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ConversationContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Conversations/{sid}".format(**self._solution) + + def _delete(self, idempotency_key: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Idempotency-Key": idempotency_key, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self, idempotency_key: Union[str, object] = values.unset) -> bool: + """ + Deletes the ConversationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete(idempotency_key=idempotency_key) + return success + + def delete_with_http_info( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the ConversationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(idempotency_key=idempotency_key) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Idempotency-Key": idempotency_key, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the ConversationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async(idempotency_key=idempotency_key) + return success + + async def delete_with_http_info_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + idempotency_key=idempotency_key + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConversationInstance: + """ + Fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + payload, _, _ = self._fetch() + return ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConversationInstance: + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + payload, _, _ = await self._fetch_async() + return ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = patch_conversation_by_id_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> ConversationInstance: + """ + Patch the ConversationInstance + + :param patch_conversation_by_id_request: The conversation fields to update + + :returns: The patched ConversationInstance + """ + payload, _, _ = self._patch( + patch_conversation_by_id_request=patch_conversation_by_id_request + ) + return ConversationInstance(self._version, payload, sid=self._solution["sid"]) + + def patch_with_http_info( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Patch the ConversationInstance and return response metadata + + :param patch_conversation_by_id_request: The conversation fields to update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch( + patch_conversation_by_id_request=patch_conversation_by_id_request + ) + instance = ConversationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = patch_conversation_by_id_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> ConversationInstance: + """ + Asynchronous coroutine to patch the ConversationInstance + + :param patch_conversation_by_id_request: The conversation fields to update + + :returns: The patched ConversationInstance + """ + payload, _, _ = await self._patch_async( + patch_conversation_by_id_request=patch_conversation_by_id_request + ) + return ConversationInstance(self._version, payload, sid=self._solution["sid"]) + + async def patch_with_http_info_async( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the ConversationInstance and return response metadata + + :param patch_conversation_by_id_request: The conversation fields to update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + patch_conversation_by_id_request=patch_conversation_by_id_request + ) + instance = ConversationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_conversation_by_id_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> ConversationInstance: + """ + Update the ConversationInstance + + :param update_conversation_by_id_request: The conversation to update + + :returns: The updated ConversationInstance + """ + payload, _, _ = self._update( + update_conversation_by_id_request=update_conversation_by_id_request + ) + return ConversationInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ConversationInstance and return response metadata + + :param update_conversation_by_id_request: The conversation to update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + update_conversation_by_id_request=update_conversation_by_id_request + ) + instance = ConversationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_conversation_by_id_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> ConversationInstance: + """ + Asynchronous coroutine to update the ConversationInstance + + :param update_conversation_by_id_request: The conversation to update + + :returns: The updated ConversationInstance + """ + payload, _, _ = await self._update_async( + update_conversation_by_id_request=update_conversation_by_id_request + ) + return ConversationInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConversationInstance and return response metadata + + :param update_conversation_by_id_request: The conversation to update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + update_conversation_by_id_request=update_conversation_by_id_request + ) + instance = ConversationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 ConversationPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ConversationInstance: + """ + Build an instance of ConversationInstance + + :param payload: Payload response from the API + """ + + return ConversationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConversationList(ListResource): + + class ConversationsV2Address(object): + """ + :ivar channel: The channel for Communication. + :ivar address: The address value formatted according to channel type: - SMS/VOICE: E.164 phone number (such as \"+18005550100\") - WHATSAPP: Phone number with whatsapp prefix (such as \"whatsapp:+18005550100\") - RCS: Sender ID or phone number with rcs prefix (such as \"rcs:brand_acme_agent\" or \"rcs:+18005550100\") - CHAT: Customer-defined string identifier + :ivar channel_id: Channel-specific ID for correlating Communications. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channel: Optional[str] = payload.get("channel") + self.address: Optional[str] = payload.get("address") + self.channel_id: Optional[str] = payload.get("channelId") + + def to_dict(self): + return { + "channel": self.channel, + "address": self.address, + "channelId": self.channel_id, + } + + class ConversationsV2ConversationsV1Bridge(object): + """ + :ivar service_id: The Conversations V1 Service SID (IS prefix). One configuration per V1 Service SID. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.service_id: Optional[str] = payload.get("serviceId") + + def to_dict(self): + return { + "serviceId": self.service_id, + } + + class ConversationsV2StatusCallbackConfig(object): + """ + :ivar url: Destination URL for webhooks. + :ivar method: HTTP method used to invoke the webhook URL. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional["ConversationInstance.str"] = payload.get("method") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + } + + class CreateConversationWithConfigRequest(object): + """ + :ivar configuration_id: The ID of an existing configuration. + :ivar name: The name of the conversation. + :ivar configuration: + :ivar participants: Optional list of Participants to create with the Conversation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration_id: Optional[str] = payload.get("configurationId") + self.name: Optional[str] = payload.get("name") + self.configuration: Optional[ + ConversationList.CreateConversationWithConfigRequestConfiguration + ] = payload.get("configuration") + self.participants: Optional[ + List[ConversationList.CreateConversationWithConfigRequestParticipants] + ] = payload.get("participants") + + def to_dict(self): + return { + "configurationId": self.configuration_id, + "name": self.name, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "participants": ( + [participants.to_dict() for participants in self.participants] + if self.participants is not None + else None + ), + } + + class CreateConversationWithConfigRequestConfiguration(object): + """ + :ivar intelligence_configuration_ids: A list of Conversational Intelligence configuration IDs. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.intelligence_configuration_ids: Optional[List[str]] = payload.get( + "intelligenceConfigurationIds" + ) + + def to_dict(self): + return { + "intelligenceConfigurationIds": self.intelligence_configuration_ids, + } + + class CreateConversationWithConfigRequestParticipants(object): + """ + :ivar name: Display name for the Participant. + :ivar type: Type of Participant in the Conversation. + :ivar profile_id: Resolved profile ID. + :ivar addresses: List of Communication addresses for the Participant. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.type: Optional["ConversationInstance.str"] = payload.get("type") + self.profile_id: Optional[str] = payload.get("profileId") + self.addresses: Optional[ + List[ + ConversationList.CreateConversationWithConfigRequestParticipantsAddresses + ] + ] = payload.get("addresses") + + def to_dict(self): + return { + "name": self.name, + "type": self.type, + "profileId": self.profile_id, + "addresses": ( + [addresses.to_dict() for addresses in self.addresses] + if self.addresses is not None + else None + ), + } + + class CreateConversationWithConfigRequestParticipantsAddresses(object): + """ + :ivar channel: + :ivar address: + :ivar channel_id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channel: Optional["ConversationInstance.str"] = payload.get("channel") + self.address: Optional[str] = payload.get("address") + self.channel_id: Optional[str] = payload.get("channelId") + + def to_dict(self): + return { + "channel": self.channel, + "address": self.address, + "channelId": self.channel_id, + } + + class PatchConversationByIdRequest(object): + """ + :ivar name: The name of the Conversation. + :ivar status: The state of the Conversation. + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.status: Optional["ConversationInstance.str"] = payload.get("status") + self.configuration: Optional[ + ConversationList.PatchConversationByIdRequestConfiguration + ] = payload.get("configuration") + + def to_dict(self): + return { + "name": self.name, + "status": self.status, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + } + + class PatchConversationByIdRequestConfiguration(object): + """ + :ivar status_callbacks: List of webhook configurations for this conversation. Send an empty array to clear all callbacks and stop webhook delivery. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.status_callbacks: Optional[ + List[ConversationList.ConversationsV2StatusCallbackConfig] + ] = payload.get("statusCallbacks") + + def to_dict(self): + return { + "statusCallbacks": ( + [ + status_callbacks.to_dict() + for status_callbacks in self.status_callbacks + ] + if self.status_callbacks is not None + else None + ), + } + + class UpdateConversationByIdRequest(object): + """ + :ivar name: The name of the Conversation. + :ivar status: The state of the Conversation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.status: Optional["ConversationInstance.str"] = payload.get("status") + + def to_dict(self): + return { + "name": self.name, + "status": self.status, + } + + def __init__(self, version: Version): + """ + Initialize the ConversationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Conversations" + + def _create( + self, + create_conversation_with_config_request: Union[ + CreateConversationWithConfigRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_conversation_with_config_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + create_conversation_with_config_request: Union[ + CreateConversationWithConfigRequest, object + ] = values.unset, + ) -> ConversationInstance: + """ + Create the ConversationInstance + + :param create_conversation_with_config_request: + + :returns: The created ConversationInstance + """ + payload, _, _ = self._create( + create_conversation_with_config_request=create_conversation_with_config_request + ) + return ConversationInstance(self._version, payload) + + def create_with_http_info( + self, + create_conversation_with_config_request: Union[ + CreateConversationWithConfigRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the ConversationInstance and return response metadata + + :param create_conversation_with_config_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_conversation_with_config_request=create_conversation_with_config_request + ) + instance = ConversationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + create_conversation_with_config_request: Union[ + CreateConversationWithConfigRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_conversation_with_config_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + create_conversation_with_config_request: Union[ + CreateConversationWithConfigRequest, object + ] = values.unset, + ) -> ConversationInstance: + """ + Asynchronously create the ConversationInstance + + :param create_conversation_with_config_request: + + :returns: The created ConversationInstance + """ + payload, _, _ = await self._create_async( + create_conversation_with_config_request=create_conversation_with_config_request + ) + return ConversationInstance(self._version, payload) + + async def create_with_http_info_async( + self, + create_conversation_with_config_request: Union[ + CreateConversationWithConfigRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ConversationInstance and return response metadata + + :param create_conversation_with_config_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_conversation_with_config_request=create_conversation_with_config_request + ) + instance = ConversationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, 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 List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to 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( + status=status, + channel_id=channel_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, 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 List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to 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 = await self.page_async( + status=status, + channel_id=channel_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConversationInstance and returns headers from first page + + + :param List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + channel_id=channel_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConversationInstance and returns headers from first page + + + :param List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + channel_id=channel_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, 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 List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + 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, + channel_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, 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 List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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, + channel_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConversationInstance and returns headers from first page + + + :param List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + channel_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConversationInstance and returns headers from first page + + + :param List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + channel_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ConversationPage: + """ + Retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param status: Filters for specific statuses + :param channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param page_size: Maximum number of items to return in a single response + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :returns: Page of ConversationInstance + """ + data = values.of( + { + "status": serialize.map(status, lambda e: e), + "channelId": channel_id, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-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, uri=self._uri, params=data) + + async def page_async( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ConversationPage: + """ + Asynchronously retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param status: Filters for specific statuses + :param channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param page_size: Maximum number of items to return in a single response + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :returns: Page of ConversationInstance + """ + data = values.of( + { + "status": serialize.map(status, lambda e: e), + "channelId": channel_id, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/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, uri=self._uri, params=data) + + def page_with_http_info( + self, + status: Union[List[str], object] = values.unset, + channel_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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: Filters for specific statuses + :param channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConversationPage, status code, and headers + """ + data = values.of( + { + "status": serialize.map(status, lambda e: e), + "channelId": channel_id, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConversationPage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union[List[str], object] = values.unset, + channel_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: Filters for specific statuses + :param channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConversationPage, status code, and headers + """ + data = values.of( + { + "status": serialize.map(status, lambda e: e), + "channelId": channel_id, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConversationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ConversationPage: + """ + Retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConversationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConversationPage: + """ + Asynchronously retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConversationPage(self._version, response) + + def get(self, sid: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param sid: + """ + return ConversationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param sid: + """ + return ConversationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v2/operation.py b/twilio/rest/conversations/v2/operation.py new file mode 100644 index 0000000000..b7e62cfa27 --- /dev/null +++ b/twilio/rest/conversations/v2/operation.py @@ -0,0 +1,274 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Conversation Orchestrator + Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.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 OperationInstance(InstanceResource): + """ + :ivar operation_id: Unique identifier for the long-running operation. + :ivar status: Current status of the operation. + :ivar created_at: Timestamp when the operation was created. + :ivar completed_at: Timestamp when the operation completed. Only present for completed or failed operations. + :ivar status_url: URL to poll for operation status. + :ivar error: + :ivar related: Named resource identifiers associated with this operation. Keys depend on the operation type: - config-create, config-update, config-delete: configurationId - conversation-delete: conversationId + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.operation_id: Optional[str] = payload.get("operationId") + self.status: Optional["OperationInstance.str"] = payload.get("status") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.completed_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("completedAt") + ) + self.status_url: Optional[str] = payload.get("statusUrl") + self.error: Optional[str] = payload.get("error") + self.related: Optional[Dict[str, str]] = payload.get("related") + + # Only set _solution if path params are provided (not None) + if sid is not None: + self._solution = { + "sid": sid, + } + + self._context: Optional[OperationContext] = None + + @property + def _proxy(self) -> "OperationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperationContext for this OperationInstance + """ + if self._context is None: + self._context = OperationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "OperationInstance": + """ + Fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperationInstance": + """ + Asynchronous coroutine to fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 OperationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the OperationContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/ControlPlane/Operations/{sid}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OperationInstance: + """ + Fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + payload, _, _ = self._fetch() + return OperationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OperationInstance: + """ + Asynchronous coroutine to fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + payload, _, _ = await self._fetch_async() + return OperationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 OperationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> OperationContext: + """ + Constructs a OperationContext + + :param sid: + """ + return OperationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> OperationContext: + """ + Constructs a OperationContext + + :param sid: + """ + return OperationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v2/participant.py b/twilio/rest/conversations/v2/participant.py new file mode 100644 index 0000000000..e752af8c91 --- /dev/null +++ b/twilio/rest/conversations/v2/participant.py @@ -0,0 +1,1137 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Conversation Orchestrator + Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ParticipantInstance(InstanceResource): + """ + :ivar id: Participant ID. + :ivar conversation_id: Conversation ID. + :ivar account_id: Account ID. + :ivar name: Participant display name. + :ivar type: Type of Participant in the Conversation. + :ivar profile_id: Profile ID. Note: This field is only resolved for `CUSTOMER` participant types, not for `HUMAN_AGENT` or `AI_AGENT` participants. + :ivar addresses: Communication addresses for this Participant. Address format varies by channel: - SMS/VOICE: E.164 phone number (such as \"+18005550100\") - EMAIL: Email address (such as \"user@example.com\") - WHATSAPP: Phone number with whatsapp prefix (such as \"whatsapp:+18005550100\") - RCS: Sender ID or phone number with rcs prefix (such as \"rcs:brand_acme_agent\" or \"rcs:+18005550100\") + :ivar created_at: Timestamp when this Participant was created. + :ivar updated_at: Timestamp when this Participant was last updated. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.conversation_id: Optional[str] = payload.get("conversationId") + self.account_id: Optional[str] = payload.get("accountId") + self.name: Optional[str] = payload.get("name") + self.type: Optional["ParticipantInstance.str"] = payload.get("type") + self.profile_id: Optional[str] = payload.get("profileId") + self.addresses: Optional[List[str]] = payload.get("addresses") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + + # Only set _solution if path params are provided (not None) + if conversation_sid is not None or sid is not None: + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context + + def 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> "ParticipantInstance": + """ + Update the ParticipantInstance + + :param update_participant_in_conversation_request: + + :returns: The updated ParticipantInstance + """ + return self._proxy.update( + update_participant_in_conversation_request=update_participant_in_conversation_request, + ) + + async def update_async( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> "ParticipantInstance": + """ + Asynchronous coroutine to update the ParticipantInstance + + :param update_participant_in_conversation_request: + + :returns: The updated ParticipantInstance + """ + return await self._proxy.update_async( + update_participant_in_conversation_request=update_participant_in_conversation_request, + ) + + def update_with_http_info( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ParticipantInstance with HTTP info + + :param update_participant_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + update_participant_in_conversation_request=update_participant_in_conversation_request, + ) + + async def update_with_http_info_async( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance with HTTP info + + :param update_participant_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + update_participant_in_conversation_request=update_participant_in_conversation_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 ParticipantContext(InstanceContext): + + def __init__(self, version: Version, conversation_sid: str, sid: str): + """ + Initialize the ParticipantContext + + :param version: Version that contains the resource + :param conversation_sid: + :param 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 _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = self._fetch() + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = await self._fetch_async() + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_participant_in_conversation_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> ParticipantInstance: + """ + Update the ParticipantInstance + + :param update_participant_in_conversation_request: + + :returns: The updated ParticipantInstance + """ + payload, _, _ = self._update( + update_participant_in_conversation_request=update_participant_in_conversation_request + ) + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ParticipantInstance and return response metadata + + :param update_participant_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + update_participant_in_conversation_request=update_participant_in_conversation_request + ) + instance = ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_participant_in_conversation_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronous coroutine to update the ParticipantInstance + + :param update_participant_in_conversation_request: + + :returns: The updated ParticipantInstance + """ + payload, _, _ = await self._update_async( + update_participant_in_conversation_request=update_participant_in_conversation_request + ) + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance and return response metadata + + :param update_participant_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + update_participant_in_conversation_request=update_participant_in_conversation_request + ) + instance = ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 ParticipantPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + + return ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ParticipantList(ListResource): + + class CreateParticipantInConversationRequest(object): + """ + :ivar name: + :ivar type: + :ivar profile_id: + :ivar addresses: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.type: Optional["ParticipantInstance.str"] = payload.get("type") + self.profile_id: Optional[str] = payload.get("profileId") + self.addresses: Optional[ + List[ParticipantList.CreateParticipantInConversationRequestAddresses] + ] = payload.get("addresses") + + def to_dict(self): + return { + "name": self.name, + "type": self.type, + "profileId": self.profile_id, + "addresses": ( + [addresses.to_dict() for addresses in self.addresses] + if self.addresses is not None + else None + ), + } + + class CreateParticipantInConversationRequestAddresses(object): + """ + :ivar channel: + :ivar address: + :ivar channel_id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channel: Optional["ParticipantInstance.str"] = payload.get("channel") + self.address: Optional[str] = payload.get("address") + self.channel_id: Optional[str] = payload.get("channelId") + + def to_dict(self): + return { + "channel": self.channel, + "address": self.address, + "channelId": self.channel_id, + } + + class UpdateParticipantInConversationRequest(object): + """ + :ivar name: + :ivar type: + :ivar profile_id: + :ivar addresses: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.type: Optional["ParticipantInstance.str"] = payload.get("type") + self.profile_id: Optional[str] = payload.get("profileId") + self.addresses: Optional[ + List[ParticipantList.CreateParticipantInConversationRequestAddresses] + ] = payload.get("addresses") + + def to_dict(self): + return { + "name": self.name, + "type": self.type, + "profileId": self.profile_id, + "addresses": ( + [addresses.to_dict() for addresses in self.addresses] + if self.addresses is not None + else None + ), + } + + def __init__(self, version: Version, conversation_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param conversation_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + } + self._uri = "/Conversations/{conversation_sid}/Participants".format( + **self._solution + ) + + def _create( + self, + create_participant_in_conversation_request: Union[ + CreateParticipantInConversationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_participant_in_conversation_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + create_participant_in_conversation_request: Union[ + CreateParticipantInConversationRequest, object + ] = values.unset, + ) -> ParticipantInstance: + """ + Create the ParticipantInstance + + :param create_participant_in_conversation_request: + + :returns: The created ParticipantInstance + """ + payload, _, _ = self._create( + create_participant_in_conversation_request=create_participant_in_conversation_request + ) + return ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def create_with_http_info( + self, + create_participant_in_conversation_request: Union[ + CreateParticipantInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the ParticipantInstance and return response metadata + + :param create_participant_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_participant_in_conversation_request=create_participant_in_conversation_request + ) + instance = ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + create_participant_in_conversation_request: Union[ + CreateParticipantInConversationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_participant_in_conversation_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + create_participant_in_conversation_request: Union[ + CreateParticipantInConversationRequest, object + ] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronously create the ParticipantInstance + + :param create_participant_in_conversation_request: + + :returns: The created ParticipantInstance + """ + payload, _, _ = await self._create_async( + create_participant_in_conversation_request=create_participant_in_conversation_request + ) + return ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + async def create_with_http_info_async( + self, + create_participant_in_conversation_request: Union[ + CreateParticipantInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ParticipantInstance and return response metadata + + :param create_participant_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_participant_in_conversation_request=create_participant_in_conversation_request + ) + instance = ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, 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 str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_token=page_token, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, 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 str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantInstance and returns headers from first page + + + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantInstance and returns headers from first page + + + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, 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 str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, 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 str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantInstance and returns headers from first page + + + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantInstance and returns headers from first page + + + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ParticipantPage: + """ + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_size: Maximum number of items to return + :param page_token: Page token for pagination + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-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, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ParticipantPage: + """ + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_size: Maximum number of items to return + :param page_token: Page token for pagination + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/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, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: Page token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: Page token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: + """ + return ParticipantContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: + """ + return ParticipantContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/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..d00ce94b1a --- /dev/null +++ b/twilio/rest/events/v1/event_type.py @@ -0,0 +1,696 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EventTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EventTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EventTypeInstance: + """ + Fetch the EventTypeInstance + + + :returns: The fetched EventTypeInstance + """ + payload, _, _ = self._fetch() + return EventTypeInstance( + self._version, + payload, + type=self._solution["type"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EventTypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EventTypeInstance( + self._version, + payload, + type=self._solution["type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> EventTypeInstance: + """ + Asynchronous coroutine to fetch the EventTypeInstance + + + :returns: The fetched EventTypeInstance + """ + payload, _, _ = await self._fetch_async() + return EventTypeInstance( + self._version, + payload, + type=self._solution["type"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EventTypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EventTypeInstance( + self._version, + payload, + type=self._solution["type"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EventTypeInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + schema_id=schema_id, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EventTypeInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + schema_id=schema_id, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EventTypeInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + schema_id=schema_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EventTypeInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + schema_id=schema_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with EventTypePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EventTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with EventTypePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EventTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..5d26d6f6ab --- /dev/null +++ b/twilio/rest/events/v1/schema/__init__.py @@ -0,0 +1,289 @@ +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.api_response import ApiResponse +from twilio.base.instance_context 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() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SchemaInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SchemaInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SchemaInstance: + """ + Fetch the SchemaInstance + + + :returns: The fetched SchemaInstance + """ + payload, _, _ = self._fetch() + return SchemaInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SchemaInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SchemaInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SchemaInstance: + """ + Asynchronous coroutine to fetch the SchemaInstance + + + :returns: The fetched SchemaInstance + """ + payload, _, _ = await self._fetch_async() + return SchemaInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SchemaInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SchemaInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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..d846590c83 --- /dev/null +++ b/twilio/rest/events/v1/schema/schema_version.py @@ -0,0 +1,675 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SchemaVersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SchemaVersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SchemaVersionInstance: + """ + Fetch the SchemaVersionInstance + + + :returns: The fetched SchemaVersionInstance + """ + payload, _, _ = self._fetch() + return SchemaVersionInstance( + self._version, + payload, + id=self._solution["id"], + schema_version=self._solution["schema_version"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SchemaVersionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SchemaVersionInstance( + self._version, + payload, + id=self._solution["id"], + schema_version=self._solution["schema_version"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SchemaVersionInstance: + """ + Asynchronous coroutine to fetch the SchemaVersionInstance + + + :returns: The fetched SchemaVersionInstance + """ + payload, _, _ = await self._fetch_async() + return SchemaVersionInstance( + self._version, + payload, + id=self._solution["id"], + schema_version=self._solution["schema_version"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SchemaVersionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SchemaVersionInstance( + self._version, + payload, + id=self._solution["id"], + schema_version=self._solution["schema_version"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SchemaVersionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SchemaVersionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SchemaVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SchemaVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SchemaVersionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SchemaVersionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SchemaVersionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SchemaVersionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..6bed98c16b --- /dev/null +++ b/twilio/rest/events/v1/sink/__init__.py @@ -0,0 +1,1184 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SinkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SinkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SinkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SinkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info(self, description: str) -> ApiResponse: + """ + Update the SinkInstance with HTTP info + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + description=description, + ) + + async def update_with_http_info_async(self, description: str) -> ApiResponse: + """ + Asynchronous coroutine to update the SinkInstance with HTTP info + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the SinkInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SinkInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SinkInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SinkInstance: + """ + Fetch the SinkInstance + + + :returns: The fetched SinkInstance + """ + payload, _, _ = self._fetch() + return SinkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SinkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SinkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SinkInstance: + """ + Asynchronous coroutine to fetch the SinkInstance + + + :returns: The fetched SinkInstance + """ + payload, _, _ = await self._fetch_async() + return SinkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SinkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SinkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, description: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Description": description, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(description=description) + return SinkInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info(self, description: str) -> ApiResponse: + """ + Update the SinkInstance and return response metadata + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(description=description) + instance = SinkInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, description: str) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Description": description, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(description=description) + return SinkInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async(self, description: str) -> ApiResponse: + """ + Asynchronous coroutine to update the SinkInstance and return response metadata + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + description=description + ) + instance = SinkInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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", + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + description=description, + sink_configuration=sink_configuration, + sink_type=sink_type, + ) + return SinkInstance(self._version, payload) + + def create_with_http_info( + self, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> ApiResponse: + """ + Create the SinkInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + description=description, + sink_configuration=sink_configuration, + sink_type=sink_type, + ) + instance = SinkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + description=description, + sink_configuration=sink_configuration, + sink_type=sink_type, + ) + return SinkInstance(self._version, payload) + + async def create_with_http_info_async( + self, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> ApiResponse: + """ + Asynchronously create the SinkInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + description=description, + sink_configuration=sink_configuration, + sink_type=sink_type, + ) + instance = SinkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SinkInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + in_use=in_use, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SinkInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + in_use=in_use, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SinkInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + in_use=in_use, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SinkInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + in_use=in_use, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with SinkPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SinkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with SinkPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SinkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..7d253b7536 --- /dev/null +++ b/twilio/rest/events/v1/sink/sink_test.py @@ -0,0 +1,146 @@ +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.api_response import ApiResponse + +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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, headers=headers + ) + + def create(self) -> SinkTestInstance: + """ + Create the SinkTestInstance + + + :returns: The created SinkTestInstance + """ + payload, _, _ = self._create() + return SinkTestInstance(self._version, payload, sid=self._solution["sid"]) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the SinkTestInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = SinkTestInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, headers=headers + ) + + async def create_async(self) -> SinkTestInstance: + """ + Asynchronously create the SinkTestInstance + + + :returns: The created SinkTestInstance + """ + payload, _, _ = await self._create_async() + return SinkTestInstance(self._version, payload, sid=self._solution["sid"]) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the SinkTestInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = SinkTestInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..aa7a169673 --- /dev/null +++ b/twilio/rest/events/v1/sink/sink_validate.py @@ -0,0 +1,168 @@ +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.api_response import ApiResponse + +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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(test_id=test_id) + return SinkValidateInstance(self._version, payload, sid=self._solution["sid"]) + + def create_with_http_info(self, test_id: str) -> ApiResponse: + """ + Create the SinkValidateInstance and return response metadata + + :param test_id: A 34 character string that uniquely identifies the test event for a Sink being validated. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(test_id=test_id) + instance = SinkValidateInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, test_id: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(test_id=test_id) + return SinkValidateInstance(self._version, payload, sid=self._solution["sid"]) + + async def create_with_http_info_async(self, test_id: str) -> ApiResponse: + """ + Asynchronously create the SinkValidateInstance and return response metadata + + :param test_id: A 34 character string that uniquely identifies the test event for a Sink being validated. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(test_id=test_id) + instance = SinkValidateInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..f494c773c9 --- /dev/null +++ b/twilio/rest/events/v1/subscription/__init__.py @@ -0,0 +1,1106 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SubscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SubscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SubscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, description: Union[str, object] = values.unset + ) -> "SubscriptionInstance": + """ + Update the SubscriptionInstance + + :param description: A human readable description for the Subscription. + + :returns: The updated SubscriptionInstance + """ + return self._proxy.update( + description=description, + ) + + async def update_async( + self, description: Union[str, object] = values.unset + ) -> "SubscriptionInstance": + """ + Asynchronous coroutine to update the SubscriptionInstance + + :param description: A human readable description for the Subscription. + + :returns: The updated SubscriptionInstance + """ + return await self._proxy.update_async( + description=description, + ) + + def update_with_http_info( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the SubscriptionInstance with HTTP info + + :param description: A human readable description for the Subscription. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + description=description, + ) + + async def update_with_http_info_async( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SubscriptionInstance with HTTP info + + :param description: A human readable description for the Subscription. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + description=description, + ) + + @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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the SubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SubscriptionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SubscriptionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SubscriptionInstance: + """ + Fetch the SubscriptionInstance + + + :returns: The fetched SubscriptionInstance + """ + payload, _, _ = self._fetch() + return SubscriptionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscriptionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SubscriptionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SubscriptionInstance: + """ + Asynchronous coroutine to fetch the SubscriptionInstance + + + :returns: The fetched SubscriptionInstance + """ + payload, _, _ = await self._fetch_async() + return SubscriptionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SubscriptionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SubscriptionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, description: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Description": description, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, description: Union[str, object] = values.unset + ) -> SubscriptionInstance: + """ + Update the SubscriptionInstance + + :param description: A human readable description for the Subscription. + + :returns: The updated SubscriptionInstance + """ + payload, _, _ = self._update(description=description) + return SubscriptionInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the SubscriptionInstance and return response metadata + + :param description: A human readable description for the Subscription. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(description=description) + instance = SubscriptionInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, description: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Description": description, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, description: Union[str, object] = values.unset + ) -> SubscriptionInstance: + """ + Asynchronous coroutine to update the SubscriptionInstance + + :param description: A human readable description for the Subscription. + + :returns: The updated SubscriptionInstance + """ + payload, _, _ = await self._update_async(description=description) + return SubscriptionInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SubscriptionInstance and return response metadata + + :param description: A human readable description for the Subscription. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + description=description + ) + instance = SubscriptionInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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]) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + description=description, sink_sid=sink_sid, types=types + ) + return SubscriptionInstance(self._version, payload) + + def create_with_http_info( + self, description: str, sink_sid: str, types: List[object] + ) -> ApiResponse: + """ + Create the SubscriptionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + description=description, sink_sid=sink_sid, types=types + ) + instance = SubscriptionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, description: str, sink_sid: str, types: List[object] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + description=description, sink_sid=sink_sid, types=types + ) + return SubscriptionInstance(self._version, payload) + + async def create_with_http_info_async( + self, description: str, sink_sid: str, types: List[object] + ) -> ApiResponse: + """ + Asynchronously create the SubscriptionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + description=description, sink_sid=sink_sid, types=types + ) + instance = SubscriptionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SubscriptionInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sink_sid=sink_sid, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SubscriptionInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sink_sid=sink_sid, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SubscriptionInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sink_sid=sink_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SubscriptionInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sink_sid=sink_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with SubscriptionPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SubscriptionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with SubscriptionPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SubscriptionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..7ad59f767b --- /dev/null +++ b/twilio/rest/events/v1/subscription/subscribed_event.py @@ -0,0 +1,1090 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SubscribedEventInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SubscribedEventInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscribedEventInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SubscribedEventInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + self, schema_version: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Update the SubscribedEventInstance with HTTP info + + :param schema_version: The schema version that the Subscription should use. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + schema_version=schema_version, + ) + + async def update_with_http_info_async( + self, schema_version: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SubscribedEventInstance with HTTP info + + :param schema_version: The schema version that the Subscription should use. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the SubscribedEventInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SubscribedEventInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SubscribedEventInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SubscribedEventInstance: + """ + Fetch the SubscribedEventInstance + + + :returns: The fetched SubscribedEventInstance + """ + payload, _, _ = self._fetch() + return SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscribedEventInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SubscribedEventInstance: + """ + Asynchronous coroutine to fetch the SubscribedEventInstance + + + :returns: The fetched SubscribedEventInstance + """ + payload, _, _ = await self._fetch_async() + return SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SubscribedEventInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, schema_version: Union[int, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "SchemaVersion": schema_version, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(schema_version=schema_version) + return SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + + def update_with_http_info( + self, schema_version: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Update the SubscribedEventInstance and return response metadata + + :param schema_version: The schema version that the Subscription should use. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(schema_version=schema_version) + instance = SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, schema_version: Union[int, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "SchemaVersion": schema_version, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(schema_version=schema_version) + return SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + + async def update_with_http_info_async( + self, schema_version: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SubscribedEventInstance and return response metadata + + :param schema_version: The schema version that the Subscription should use. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + schema_version=schema_version + ) + instance = SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(type=type, schema_version=schema_version) + return SubscribedEventInstance( + self._version, payload, subscription_sid=self._solution["subscription_sid"] + ) + + def create_with_http_info( + self, type: str, schema_version: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Create the SubscribedEventInstance and return response metadata + + :param type: Type of event being subscribed to. + :param schema_version: The schema version that the Subscription should use. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, schema_version=schema_version + ) + instance = SubscribedEventInstance( + self._version, payload, subscription_sid=self._solution["subscription_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, type: str, schema_version: Union[int, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + type=type, schema_version=schema_version + ) + return SubscribedEventInstance( + self._version, payload, subscription_sid=self._solution["subscription_sid"] + ) + + async def create_with_http_info_async( + self, type: str, schema_version: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the SubscribedEventInstance and return response metadata + + :param type: Type of event being subscribed to. + :param schema_version: The schema version that the Subscription should use. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, schema_version=schema_version + ) + instance = SubscribedEventInstance( + self._version, payload, subscription_sid=self._solution["subscription_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SubscribedEventInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SubscribedEventInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SubscribedEventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SubscribedEventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SubscribedEventPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SubscribedEventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SubscribedEventPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SubscribedEventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 d2ea8d037f..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'], limits['page_limit']) - - def list(self, from_=values.unset, to=values.unset, - date_created_on_or_before=values.unset, - date_created_after=values.unset, limit=None, page_size=None): - """ - Lists FaxInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode from_: 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 461e26fdd2..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists FaxMediaInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.fax.v1.fax.fax_media.FaxMediaInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of FaxMediaInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of FaxMediaInstance - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaPage - """ - 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..003b309a89 --- /dev/null +++ b/twilio/rest/flex_api/v1/assessments.py @@ -0,0 +1,1210 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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[str] = payload.get("offset") + self.report: Optional[bool] = payload.get("report") + self.weight: Optional[str] = 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[str] = 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 update_with_http_info( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the AssessmentsInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) + + async def update_with_http_info_async( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AssessmentsInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) + return AssessmentsInstance( + self._version, payload, assessment_sid=self._solution["assessment_sid"] + ) + + def update_with_http_info( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the AssessmentsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) + instance = AssessmentsInstance( + self._version, payload, assessment_sid=self._solution["assessment_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) + return AssessmentsInstance( + self._version, payload, assessment_sid=self._solution["assessment_sid"] + ) + + async def update_with_http_info_async( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AssessmentsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) + instance = AssessmentsInstance( + self._version, payload, assessment_sid=self._solution["assessment_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + category_sid=category_sid, + category_name=category_name, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + metric_id=metric_id, + metric_name=metric_name, + answer_text=answer_text, + answer_id=answer_id, + questionnaire_sid=questionnaire_sid, + authorization=authorization, + ) + return AssessmentsInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the AssessmentsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + category_sid=category_sid, + category_name=category_name, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + metric_id=metric_id, + metric_name=metric_name, + answer_text=answer_text, + answer_id=answer_id, + questionnaire_sid=questionnaire_sid, + authorization=authorization, + ) + instance = AssessmentsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + category_sid=category_sid, + category_name=category_name, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + metric_id=metric_id, + metric_name=metric_name, + answer_text=answer_text, + answer_id=answer_id, + questionnaire_sid=questionnaire_sid, + authorization=authorization, + ) + return AssessmentsInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the AssessmentsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + category_sid=category_sid, + category_name=category_name, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + metric_id=metric_id, + metric_name=metric_name, + answer_text=answer_text, + answer_id=answer_id, + questionnaire_sid=questionnaire_sid, + authorization=authorization, + ) + instance = AssessmentsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AssessmentsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AssessmentsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AssessmentsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AssessmentsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with AssessmentsPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssessmentsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with AssessmentsPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssessmentsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 dccfac715f..0f223bc426 100644 --- a/twilio/rest/flex_api/v1/channel.py +++ b/twilio/rest/flex_api/v1/channel.py @@ -1,403 +1,1026 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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") + ) + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[ChannelContext] = None - def __init__(self, version): + @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 + + :returns: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() - :param Version version: Version that contains the resource + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "ChannelInstance": + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelInstance": + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return await self._proxy.fetch_async() - :returns: twilio.rest.flex_api.v1.channel.ChannelList - :rtype: twilio.rest.flex_api.v1.channel.ChannelList + def fetch_with_http_info(self) -> ApiResponse: """ - super(ChannelList, self).__init__(version) + Fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ChannelContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex chat channel resource to fetch. + """ + super().__init__(version) # Path Solution - self._solution = {} - self._uri = '/Channels'.format(**self._solution) + self._solution = { + "sid": sid, + } + self._uri = "/Channels/{sid}".format(**self._solution) - def stream(self, limit=None, page_size=None): + def _delete(self) -> tuple: """ - 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. + Internal helper for delete operation - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.flex_api.v1.channel.ChannelInstance] + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the ChannelInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success - def list(self, limit=None, page_size=None): + def delete_with_http_info(self) -> ApiResponse: """ - Lists ChannelInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the ChannelInstance and return response metadata - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Retrieve a single page of ChannelInstance 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 + headers = values.of({}) - :returns: Page of ChannelInstance - :rtype: twilio.rest.flex_api.v1.channel.ChannelPage + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Asynchronous coroutine that deletes the ChannelInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return ChannelPage(self._version, response, self._solution) + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success - def get_page(self, target_url): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Retrieve a specific page of ChannelInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the ChannelInstance and return response metadata - :param str target_url: API-generated URL for the requested results page - :returns: Page of ChannelInstance - :rtype: twilio.rest.flex_api.v1.channel.ChannelPage + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) - return ChannelPage(self._version, response, self._solution) + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + payload, _, _ = self._fetch() + return ChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - 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 fetch_with_http_info(self) -> ApiResponse: """ - Create the ChannelInstance + Fetch the ChannelInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - 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, status_code, headers = self._fetch() + instance = ChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + Returns: + tuple: (payload, status_code, headers) + """ - return ChannelInstance(self._version, payload, ) + headers = values.of({}) - def get(self, sid): + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ChannelInstance: """ - Constructs a ChannelContext + Asynchronous coroutine to fetch 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: The fetched ChannelInstance """ - return ChannelContext(self._version, sid=sid, ) + payload, _, _ = await self._fetch_async() + return ChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __call__(self, sid): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Constructs a ChannelContext + Asynchronous coroutine to fetch the ChannelInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return ChannelContext(self._version, sid=sid, ) + payload, status_code, headers = await self._fetch_async() + instance = ChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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): - """ """ - def __init__(self, version, response, solution): + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: """ - Initialize the ChannelPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Build an instance of ChannelInstance - :returns: twilio.rest.flex_api.v1.channel.ChannelPage - :rtype: twilio.rest.flex_api.v1.channel.ChannelPage + :param payload: Payload response from the API """ - super(ChannelPage, self).__init__(version, response) - # Path Solution - self._solution = solution + return ChannelInstance(self._version, payload) - def get_instance(self, payload): + def __repr__(self) -> str: """ - Build an instance of ChannelInstance + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + - :param dict payload: Payload response from the API +class ChannelList(ListResource): - :returns: twilio.rest.flex_api.v1.channel.ChannelInstance - :rtype: twilio.rest.flex_api.v1.channel.ChannelInstance + def __init__(self, version: Version): """ - return ChannelInstance(self._version, payload, ) + Initialize the ChannelList + + :param version: Version that contains the resource - def __repr__(self): """ - Provide a friendly representation + super().__init__(version) + + self._uri = "/Channels" + + def _create( + self, + flex_flow_sid: str, + identity: str, + chat_user_friendly_name: str, + chat_friendly_name: str, + target: Union[str, object] = values.unset, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + task_attributes: Union[str, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + data = values.of( + { + "FlexFlowSid": flex_flow_sid, + "Identity": identity, + "ChatUserFriendlyName": chat_user_friendly_name, + "ChatFriendlyName": chat_friendly_name, + "Target": target, + "ChatUniqueName": chat_unique_name, + "PreEngagementData": pre_engagement_data, + "TaskSid": task_sid, + "TaskAttributes": task_attributes, + "LongLived": serialize.boolean_to_string(long_lived), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" -class ChannelContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, sid): + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - Initialize the ChannelContext + 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. - :param Version version: Version that contains the resource - :param sid: The SID that identifies the Flex chat channel resource to fetch + :returns: The created ChannelInstance + """ + payload, _, _ = self._create( + flex_flow_sid=flex_flow_sid, + identity=identity, + chat_user_friendly_name=chat_user_friendly_name, + chat_friendly_name=chat_friendly_name, + target=target, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + task_sid=task_sid, + task_attributes=task_attributes, + long_lived=long_lived, + ) + return ChannelInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + flex_flow_sid=flex_flow_sid, + identity=identity, + chat_user_friendly_name=chat_user_friendly_name, + chat_friendly_name=chat_friendly_name, + target=target, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + task_sid=task_sid, + task_attributes=task_attributes, + long_lived=long_lived, + ) + instance = ChannelInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation - :returns: twilio.rest.flex_api.v1.channel.ChannelContext - :rtype: twilio.rest.flex_api.v1.channel.ChannelContext + Returns: + tuple: (payload, status_code, headers) """ - super(ChannelContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Channels/{sid}'.format(**self._solution) + data = values.of( + { + "FlexFlowSid": flex_flow_sid, + "Identity": identity, + "ChatUserFriendlyName": chat_user_friendly_name, + "ChatFriendlyName": chat_friendly_name, + "Target": target, + "ChatUniqueName": chat_unique_name, + "PreEngagementData": pre_engagement_data, + "TaskSid": task_sid, + "TaskAttributes": task_attributes, + "LongLived": serialize.boolean_to_string(long_lived), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def fetch(self): + 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: """ - Fetch the 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 fetched ChannelInstance - :rtype: twilio.rest.flex_api.v1.channel.ChannelInstance + :returns: The created ChannelInstance + """ + payload, _, _ = await self._create_async( + flex_flow_sid=flex_flow_sid, + identity=identity, + chat_user_friendly_name=chat_user_friendly_name, + chat_friendly_name=chat_friendly_name, + target=target, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + task_sid=task_sid, + task_attributes=task_attributes, + long_lived=long_lived, + ) + return ChannelInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronously create the ChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + flex_flow_sid=flex_flow_sid, + identity=identity, + chat_user_friendly_name=chat_user_friendly_name, + chat_friendly_name=chat_friendly_name, + target=target, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + task_sid=task_sid, + task_attributes=task_attributes, + long_lived=long_lived, + ) + instance = ChannelInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: + """ + Streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - return ChannelInstance(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) - def delete(self): + :returns: Generator that will yield up to limit results """ - Deletes the ChannelInstance + limits = self._version.read_limits(limit, page_size) + page = self.page(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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelInstance]: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Asynchronously streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - 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 + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Streams ChannelInstance and returns headers from first page -class ChannelInstance(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, sid=None): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Initialize the ChannelInstance + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: twilio.rest.flex_api.v1.channel.ChannelInstance - :rtype: twilio.rest.flex_api.v1.channel.ChannelInstance + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(ChannelInstance, self).__init__(version) + Asynchronously streams ChannelInstance and returns headers from first page - # 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')), - } - # Context - self._context = None - self._solution = {'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: tuple of (generator, status_code, headers) where generator yields instances """ - 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_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :returns: ChannelContext for this ChannelInstance - :rtype: twilio.rest.flex_api.v1.channel.ChannelContext + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: """ - if self._context is None: - self._context = ChannelContext(self._version, sid=self._solution['sid'], ) - return self._context + 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 account_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 Account that created the resource and owns this Workflow - :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['account_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 flex_flow_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 FlexFlow - :rtype: unicode + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['flex_flow_sid'] + Lists ChannelInstance and returns headers from first page - @property - def 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: ApiResponse with list of instances, status code, and headers """ - :returns: The unique string that identifies the resource - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['sid'] + Asynchronously lists ChannelInstance and returns headers from first page - @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: ApiResponse with list of instances, status code, and headers """ - :returns: The SID of the chat user - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['user_sid'] + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately - @property - def task_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 ChannelInstance """ - :returns: The SID of the TaskRouter task - :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 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: """ - return self._properties['task_sid'] + Asynchronously retrieve a single page of ChannelInstance 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 ChannelInstance """ - :returns: The absolute URL of the Flex chat channel 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 ChannelPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['url'] + Retrieve a single page with response metadata - @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: ApiResponse with ChannelPage, status code, and headers """ - :returns: The ISO 8601 date and time in GMT when the Flex chat channel 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChannelPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_created'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with ChannelPage, status code, and headers """ - :returns: The ISO 8601 date and time in GMT when the Flex chat channel 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChannelPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ChannelPage: """ - return self._properties['date_updated'] + Retrieve a specific page of ChannelInstance 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 ChannelInstance """ - Fetch the ChannelInstance + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response) - :returns: The fetched ChannelInstance - :rtype: twilio.rest.flex_api.v1.channel.ChannelInstance + async def get_page_async(self, target_url: str) -> ChannelPage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of ChannelInstance """ - Deletes the ChannelInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> ChannelContext: """ - return self._proxy.delete() + Constructs a ChannelContext + + :param sid: The SID of the Flex chat channel resource to fetch. + """ + return ChannelContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: The SID of the Flex chat channel resource to fetch. + """ + return ChannelContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 01585bb857..6e8f586a01 100644 --- a/twilio/rest/flex_api/v1/configuration.py +++ b/twilio/rest/flex_api/v1/configuration.py @@ -1,575 +1,592 @@ -# 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.api_response import ApiResponse 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 ConfigurationList(ListResource): - """ """ +class ConfigurationInstance(InstanceResource): - def __init__(self, version): + class Status(object): + OK = "ok" + INPROGRESS = "inprogress" + NOTSTARTED = "notstarted" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Configuration resource. + :ivar date_created: The date and time in GMT when the Configuration resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Configuration resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar attributes: An object that contains application-specific data. + :ivar status: + :ivar taskrouter_workspace_sid: The SID of the TaskRouter Workspace. + :ivar taskrouter_target_workflow_sid: The SID of the TaskRouter target Workflow. + :ivar taskrouter_target_taskqueue_sid: The SID of the TaskRouter Target TaskQueue. + :ivar taskrouter_taskqueues: The list of TaskRouter TaskQueues. + :ivar taskrouter_skills: The Skill description for TaskRouter workers. + :ivar taskrouter_worker_channels: The TaskRouter default channel capacities and availability for workers. + :ivar taskrouter_worker_attributes: The TaskRouter Worker attributes. + :ivar taskrouter_offline_activity_sid: The TaskRouter SID of the offline activity. + :ivar runtime_domain: The URL where the Flex instance is hosted. + :ivar messaging_service_instance_sid: The SID of the Messaging service instance. + :ivar chat_service_instance_sid: The SID of the chat service this user belongs to. + :ivar flex_service_instance_sid: The SID of the Flex service instance. + :ivar flex_instance_sid: The SID of the Flex instance. + :ivar ui_language: The primary language of the Flex UI. + :ivar ui_attributes: The object that describes Flex UI characteristics and settings. + :ivar ui_dependencies: The object that defines the NPM packages and versions to be used in Hosted Flex. + :ivar ui_version: The Pinned UI version. + :ivar service_version: The Flex Service version. + :ivar call_recording_enabled: Whether call recording is enabled. + :ivar call_recording_webhook_url: The call recording webhook URL. + :ivar crm_enabled: Whether CRM is present for Flex. + :ivar crm_type: The CRM type. + :ivar crm_callback_url: The CRM Callback URL. + :ivar crm_fallback_url: The CRM Fallback URL. + :ivar crm_attributes: An object that contains the CRM attributes. + :ivar public_attributes: The list of public attributes, which are visible to unauthenticated clients. + :ivar plugin_service_enabled: Whether the plugin service enabled. + :ivar plugin_service_attributes: The plugin service attributes. + :ivar integrations: A list of objects that contain the configurations for the Integrations supported in this configuration. + :ivar outbound_call_flows: The list of outbound call flows. + :ivar serverless_service_sids: The list of serverless service SIDs. + :ivar queue_stats_configuration: Configurable parameters for Queues Statistics. + :ivar notifications: Configurable parameters for Notifications. + :ivar markdown: Configurable parameters for Markdown. + :ivar url: The absolute URL of the Configuration resource. + :ivar flex_insights_hr: Object with enabled/disabled flag with list of workspaces. + :ivar flex_insights_drilldown: Setting this to true will redirect Flex UI to the URL set in flex_url + :ivar flex_url: URL to redirect to in case drilldown is enabled. + :ivar channel_configs: Settings for different limits for Flex Conversations channels attachments. + :ivar debugger_integration: Configurable parameters for Debugger Integration. + :ivar flex_ui_status_report: Configurable parameters for Flex UI Status report. + :ivar agent_conv_end_methods: Agent conversation end methods. + :ivar citrix_voice_vdi: Citrix voice vdi configuration and settings. + :ivar offline_config: Presence and presence ttl configuration + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.status: Optional["ConfigurationInstance.Status"] = payload.get("status") + self.taskrouter_workspace_sid: Optional[str] = payload.get( + "taskrouter_workspace_sid" + ) + self.taskrouter_target_workflow_sid: Optional[str] = payload.get( + "taskrouter_target_workflow_sid" + ) + self.taskrouter_target_taskqueue_sid: Optional[str] = payload.get( + "taskrouter_target_taskqueue_sid" + ) + self.taskrouter_taskqueues: Optional[List[Dict[str, object]]] = payload.get( + "taskrouter_taskqueues" + ) + self.taskrouter_skills: Optional[List[Dict[str, object]]] = payload.get( + "taskrouter_skills" + ) + self.taskrouter_worker_channels: Optional[Dict[str, object]] = payload.get( + "taskrouter_worker_channels" + ) + self.taskrouter_worker_attributes: Optional[Dict[str, object]] = payload.get( + "taskrouter_worker_attributes" + ) + self.taskrouter_offline_activity_sid: Optional[str] = payload.get( + "taskrouter_offline_activity_sid" + ) + self.runtime_domain: Optional[str] = payload.get("runtime_domain") + self.messaging_service_instance_sid: Optional[str] = payload.get( + "messaging_service_instance_sid" + ) + self.chat_service_instance_sid: Optional[str] = payload.get( + "chat_service_instance_sid" + ) + self.flex_service_instance_sid: Optional[str] = payload.get( + "flex_service_instance_sid" + ) + self.flex_instance_sid: Optional[str] = payload.get("flex_instance_sid") + self.ui_language: Optional[str] = payload.get("ui_language") + self.ui_attributes: Optional[Dict[str, object]] = payload.get("ui_attributes") + self.ui_dependencies: Optional[Dict[str, object]] = payload.get( + "ui_dependencies" + ) + self.ui_version: Optional[str] = payload.get("ui_version") + self.service_version: Optional[str] = payload.get("service_version") + self.call_recording_enabled: Optional[bool] = payload.get( + "call_recording_enabled" + ) + self.call_recording_webhook_url: Optional[str] = payload.get( + "call_recording_webhook_url" + ) + self.crm_enabled: Optional[bool] = payload.get("crm_enabled") + self.crm_type: Optional[str] = payload.get("crm_type") + self.crm_callback_url: Optional[str] = payload.get("crm_callback_url") + self.crm_fallback_url: Optional[str] = payload.get("crm_fallback_url") + self.crm_attributes: Optional[Dict[str, object]] = payload.get("crm_attributes") + self.public_attributes: Optional[Dict[str, object]] = payload.get( + "public_attributes" + ) + self.plugin_service_enabled: Optional[bool] = payload.get( + "plugin_service_enabled" + ) + self.plugin_service_attributes: Optional[Dict[str, object]] = payload.get( + "plugin_service_attributes" + ) + self.integrations: Optional[List[Dict[str, object]]] = payload.get( + "integrations" + ) + self.outbound_call_flows: Optional[Dict[str, object]] = payload.get( + "outbound_call_flows" + ) + self.serverless_service_sids: Optional[List[str]] = payload.get( + "serverless_service_sids" + ) + self.queue_stats_configuration: Optional[Dict[str, object]] = payload.get( + "queue_stats_configuration" + ) + self.notifications: Optional[Dict[str, object]] = payload.get("notifications") + self.markdown: Optional[Dict[str, object]] = payload.get("markdown") + self.url: Optional[str] = payload.get("url") + self.flex_insights_hr: Optional[Dict[str, object]] = payload.get( + "flex_insights_hr" + ) + self.flex_insights_drilldown: Optional[bool] = payload.get( + "flex_insights_drilldown" + ) + self.flex_url: Optional[str] = payload.get("flex_url") + self.channel_configs: Optional[List[Dict[str, object]]] = payload.get( + "channel_configs" + ) + self.debugger_integration: Optional[Dict[str, object]] = payload.get( + "debugger_integration" + ) + self.flex_ui_status_report: Optional[Dict[str, object]] = payload.get( + "flex_ui_status_report" + ) + self.agent_conv_end_methods: Optional[Dict[str, object]] = payload.get( + "agent_conv_end_methods" + ) + self.citrix_voice_vdi: Optional[Dict[str, object]] = payload.get( + "citrix_voice_vdi" + ) + self.offline_config: Optional[Dict[str, object]] = payload.get("offline_config") + + self._context: Optional[ConfigurationContext] = None + + @property + def _proxy(self) -> "ConfigurationContext": """ - Initialize the ConfigurationList + 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: ConfigurationContext for this ConfigurationInstance + """ + if self._context is None: + self._context = ConfigurationContext( + self._version, + ) + return self._context - :returns: twilio.rest.flex_api.v1.configuration.ConfigurationList - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationList + def fetch( + self, ui_version: Union[str, object] = values.unset + ) -> "ConfigurationInstance": """ - super(ConfigurationList, self).__init__(version) + Fetch the ConfigurationInstance - # Path Solution - self._solution = {} + :param ui_version: The Pinned UI version of the Configuration resource to fetch. - def get(self): + :returns: The fetched ConfigurationInstance """ - Constructs a ConfigurationContext + return self._proxy.fetch( + ui_version=ui_version, + ) - :returns: twilio.rest.flex_api.v1.configuration.ConfigurationContext - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationContext + async def fetch_async( + self, ui_version: Union[str, object] = values.unset + ) -> "ConfigurationInstance": """ - return ConfigurationContext(self._version, ) + Asynchronous coroutine to fetch the ConfigurationInstance + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. - def __call__(self): + :returns: The fetched ConfigurationInstance """ - Constructs a ConfigurationContext + return await self._proxy.fetch_async( + ui_version=ui_version, + ) + + def fetch_with_http_info( + self, ui_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the ConfigurationInstance with HTTP info + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. - :returns: twilio.rest.flex_api.v1.configuration.ConfigurationContext - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationContext + :returns: ApiResponse with instance, status code, and headers """ - return ConfigurationContext(self._version, ) + return self._proxy.fetch_with_http_info( + ui_version=ui_version, + ) - def __repr__(self): + async def fetch_with_http_info_async( + self, ui_version: Union[str, object] = values.unset + ) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the ConfigurationInstance with HTTP info - :returns: Machine friendly representation - :rtype: str + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :returns: ApiResponse with instance, status code, and headers """ - return '' + return await self._proxy.fetch_with_http_info_async( + ui_version=ui_version, + ) + def update( + self, body: Union[object, object] = values.unset + ) -> "ConfigurationInstance": + """ + Update the ConfigurationInstance -class ConfigurationPage(Page): - """ """ + :param body: - def __init__(self, version, response, solution): + :returns: The updated ConfigurationInstance """ - Initialize the ConfigurationPage + return self._proxy.update( + body=body, + ) + + async def update_async( + self, body: Union[object, object] = values.unset + ) -> "ConfigurationInstance": + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param body: - :param Version version: Version that contains the resource - :param Response response: Response from the API + :returns: The updated ConfigurationInstance + """ + return await self._proxy.update_async( + body=body, + ) - :returns: twilio.rest.flex_api.v1.configuration.ConfigurationPage - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationPage + def update_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: """ - super(ConfigurationPage, self).__init__(version, response) + Update the ConfigurationInstance with HTTP info + + :param body: - # Path Solution - self._solution = solution + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + body=body, + ) - def get_instance(self, payload): + async def update_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: """ - Build an instance of ConfigurationInstance + Asynchronous coroutine to update the ConfigurationInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return ConfigurationInstance(self._version, payload, ) + return await self._proxy.update_with_http_info_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) -> tuple: """ - Fetch the ConfigurationInstance - - :param unicode ui_version: The Pinned UI version of the Configuration resource to fetch + Internal helper for fetch operation - :returns: The fetched ConfigurationInstance - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of({'UiVersion': ui_version, }) - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + params = values.of( + { + "UiVersion": ui_version, + } + ) - return ConfigurationInstance(self._version, payload, ) + headers = values.of({}) - def create(self): - """ - Create the ConfigurationInstance + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) - :returns: The created ConfigurationInstance - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance + def fetch( + self, ui_version: Union[str, object] = values.unset + ) -> ConfigurationInstance: """ - payload = self._version.create(method='POST', uri=self._uri, ) + Fetch the ConfigurationInstance - return ConfigurationInstance(self._version, payload, ) + :param ui_version: The Pinned UI version of the Configuration resource to fetch. - def update(self): + :returns: The fetched ConfigurationInstance """ - Update the ConfigurationInstance + payload, _, _ = self._fetch(ui_version=ui_version) + return ConfigurationInstance( + self._version, + payload, + ) - :returns: The updated ConfigurationInstance - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance + def fetch_with_http_info( + self, ui_version: Union[str, object] = values.unset + ) -> ApiResponse: """ - payload = self._version.update(method='POST', uri=self._uri, ) + Fetch the ConfigurationInstance and return response metadata - return ConfigurationInstance(self._version, payload, ) + :param ui_version: The Pinned UI version of the Configuration resource to fetch. - def __repr__(self): + :returns: ApiResponse with instance, status code, and headers """ - Provide a friendly representation + payload, status_code, headers = self._fetch(ui_version=ui_version) + instance = ConfigurationInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: Machine friendly representation - :rtype: str + async def _fetch_async( + self, ui_version: Union[str, object] = values.unset + ) -> tuple: """ - 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" + Internal async helper for fetch operation - 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'), - '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'), - 'wfm_integrations': payload.get('wfm_integrations'), - 'queue_stats_configuration': payload.get('queue_stats_configuration'), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = {} - - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - 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 + params = values.of( + { + "UiVersion": ui_version, + } + ) - @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 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'] + headers["Accept"] = "application/json" - @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'] + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - @property - def attributes(self): + async def fetch_async( + self, ui_version: Union[str, object] = values.unset + ) -> ConfigurationInstance: """ - :returns: An object that contains application-specific data - :rtype: dict - """ - return self._properties['attributes'] + Asynchronous coroutine to fetch the ConfigurationInstance - @property - def status(self): - """ - :returns: The status of the Flex onboarding - :rtype: ConfigurationInstance.Status - """ - return self._properties['status'] + :param ui_version: The Pinned UI version of the Configuration resource to fetch. - @property - def taskrouter_workspace_sid(self): - """ - :returns: The SID of the TaskRouter Workspace - :rtype: unicode + :returns: The fetched ConfigurationInstance """ - return self._properties['taskrouter_workspace_sid'] + payload, _, _ = await self._fetch_async(ui_version=ui_version) + 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_with_http_info_async( + self, ui_version: Union[str, object] = values.unset + ) -> ApiResponse: """ - return self._properties['taskrouter_target_workflow_sid'] + Asynchronous coroutine to fetch the ConfigurationInstance and return response metadata - @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: ApiResponse with instance, status code, and headers """ - return self._properties['taskrouter_taskqueues'] + payload, status_code, headers = await self._fetch_async(ui_version=ui_version) + instance = ConfigurationInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def taskrouter_skills(self): + def _update(self, body: Union[object, object] = values.unset) -> tuple: """ - :returns: The Skill description for TaskRouter workers - :rtype: dict - """ - return self._properties['taskrouter_skills'] + Internal helper for update operation - @property - def taskrouter_worker_channels(self): - """ - :returns: The TaskRouter default channel capacities and availability for workers - :rtype: dict + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['taskrouter_worker_channels'] + data = body.to_dict() - @property - def taskrouter_worker_attributes(self): - """ - :returns: The TaskRouter Worker attributes - :rtype: dict - """ - return self._properties['taskrouter_worker_attributes'] + headers = values.of({}) - @property - def taskrouter_offline_activity_sid(self): - """ - :returns: The TaskRouter SID of the offline activity - :rtype: unicode - """ - return self._properties['taskrouter_offline_activity_sid'] + headers["Content-Type"] = "application/json" - @property - def runtime_domain(self): - """ - :returns: The URL where the Flex instance is hosted - :rtype: unicode - """ - return self._properties['runtime_domain'] + headers["Accept"] = "application/json" - @property - def messaging_service_instance_sid(self): - """ - :returns: The SID of the Messaging service instance - :rtype: unicode - """ - return self._properties['messaging_service_instance_sid'] + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def chat_service_instance_sid(self): - """ - :returns: The SID of the chat service this user belongs to - :rtype: unicode + def update( + self, body: Union[object, object] = values.unset + ) -> ConfigurationInstance: """ - return self._properties['chat_service_instance_sid'] + Update the ConfigurationInstance - @property - def ui_language(self): - """ - :returns: The primary language of the Flex UI - :rtype: unicode - """ - return self._properties['ui_language'] + :param body: - @property - def ui_attributes(self): - """ - :returns: The object that describes Flex UI characteristics and settings - :rtype: dict + :returns: The updated ConfigurationInstance """ - return self._properties['ui_attributes'] + payload, _, _ = self._update(body=body) + return ConfigurationInstance(self._version, payload) - @property - def ui_dependencies(self): + def update_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: """ - :returns: The object that defines the NPM packages and versions to be used in Hosted Flex - :rtype: dict - """ - return self._properties['ui_dependencies'] + Update the ConfigurationInstance and return response metadata - @property - def ui_version(self): - """ - :returns: The Pinned UI version - :rtype: unicode - """ - return self._properties['ui_version'] + :param body: - @property - def service_version(self): + :returns: ApiResponse with instance, status code, and headers """ - :returns: The Flex Service version - :rtype: unicode - """ - return self._properties['service_version'] + payload, status_code, headers = self._update(body=body) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def call_recording_enabled(self): - """ - :returns: Whether call recording is enabled - :rtype: bool + async def _update_async(self, body: Union[object, object] = values.unset) -> tuple: """ - return self._properties['call_recording_enabled'] + Internal async helper for update operation - @property - def call_recording_webhook_url(self): - """ - :returns: The call recording webhook URL - :rtype: unicode + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['call_recording_webhook_url'] + data = body.to_dict() - @property - def crm_enabled(self): - """ - :returns: Whether CRM is present for Flex - :rtype: bool - """ - return self._properties['crm_enabled'] + headers = values.of({}) - @property - def crm_type(self): - """ - :returns: The CRM Type - :rtype: unicode - """ - return self._properties['crm_type'] + headers["Content-Type"] = "application/json" - @property - def crm_callback_url(self): - """ - :returns: The CRM Callback URL - :rtype: unicode - """ - return self._properties['crm_callback_url'] + headers["Accept"] = "application/json" - @property - def crm_fallback_url(self): - """ - :returns: The CRM Fallback URL - :rtype: unicode - """ - return self._properties['crm_fallback_url'] + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def crm_attributes(self): - """ - :returns: An object that contains the CRM attributes - :rtype: dict + async def update_async( + self, body: Union[object, object] = values.unset + ) -> ConfigurationInstance: """ - return self._properties['crm_attributes'] + Asynchronous coroutine to update the ConfigurationInstance - @property - def public_attributes(self): - """ - :returns: The list of public attributes - :rtype: dict - """ - return self._properties['public_attributes'] + :param body: - @property - def plugin_service_enabled(self): - """ - :returns: Whether the plugin service enabled - :rtype: bool + :returns: The updated ConfigurationInstance """ - return self._properties['plugin_service_enabled'] + payload, _, _ = await self._update_async(body=body) + return ConfigurationInstance(self._version, payload) - @property - def plugin_service_attributes(self): - """ - :returns: The plugin service attributes - :rtype: dict + async def update_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: """ - return self._properties['plugin_service_attributes'] + Asynchronous coroutine to update the ConfigurationInstance and return response metadata - @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'] + :param body: - @property - def outbound_call_flows(self): - """ - :returns: The list of outbound call flows - :rtype: dict + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['outbound_call_flows'] + payload, status_code, headers = await self._update_async(body=body) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def serverless_service_sids(self): - """ - :returns: The list of serverless service SIDs - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['serverless_service_sids'] + Provide a friendly representation - @property - def wfm_integrations(self): - """ - :returns: A list of objects that contain the configurations for the WFM Integrations supported in this configuration - :rtype: dict + :returns: Machine friendly representation """ - return self._properties['wfm_integrations'] - @property - def queue_stats_configuration(self): - """ - :returns: Configurable parameters for Queues Statistics - :rtype: dict - """ - return self._properties['queue_stats_configuration'] + return "" - @property - def url(self): - """ - :returns: The absolute URL of the Configuration resource - :rtype: unicode - """ - return self._properties['url'] - def fetch(self, ui_version=values.unset): +class ConfigurationList(ListResource): + + 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 b91fda14d6..35f61b0683 100644 --- a/twilio/rest/flex_api/v1/flex_flow.py +++ b/twilio/rest/flex_api/v1/flex_flow.py @@ -1,577 +1,734 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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" + + class IntegrationType(object): + STUDIO = "studio" + EXTERNAL = "external" + TASK = "task" - :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 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") - :returns: twilio.rest.flex_api.v1.flex_flow.FlexFlowList - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowList - """ - super(FlexFlowList, self).__init__(version) + self._solution = { + "sid": sid or self.sid, + } - # Path Solution - self._solution = {} - self._uri = '/FlexFlows'.format(**self._solution) + 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'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, friendly_name=values.unset, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists 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 delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of FlexFlowInstance records from the API. - Request is executed immediately + Deletes the FlexFlowInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - data = values.of({ - 'FriendlyName': friendly_name, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.delete_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlexFlowInstance with HTTP info - return FlexFlowPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with success boolean, status code, and headers """ - Retrieve a specific page of FlexFlowInstance records from the API. - Request is executed immediately + return await self._proxy.delete_with_http_info_async() - :param str target_url: API-generated URL for the requested results page - - :returns: Page of FlexFlowInstance - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowPage + def fetch(self) -> "FlexFlowInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Fetch the FlexFlowInstance - return FlexFlowPage(self._version, response, self._solution) - 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 fetched FlexFlowInstance """ - Create 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 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: Whether new channels are long-lived - :param bool janitor_enabled: Boolean flag for enabling or disabling the Janitor - :param unicode integration_retry_count: The number of times to retry the webhook if the first attempt fails + return self._proxy.fetch() - :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): + async def fetch_async(self) -> "FlexFlowInstance": """ - Constructs a FlexFlowContext + Asynchronous coroutine to fetch the FlexFlowInstance - :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 """ - return FlexFlowContext(self._version, sid=sid, ) + return await self._proxy.fetch_async() - def __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a FlexFlowContext + Fetch the FlexFlowInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return FlexFlowContext(self._version, sid=sid, ) + return self._proxy.fetch_with_http_info() - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' + Asynchronous coroutine to fetch the FlexFlowInstance with HTTP info -class FlexFlowPage(Page): - """ """ + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() - def __init__(self, version, response, solution): + 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": """ - Initialize the FlexFlowPage + Update the FlexFlowInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API + :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: twilio.rest.flex_api.v1.flex_flow.FlexFlowPage - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowPage + :returns: The updated FlexFlowInstance """ - super(FlexFlowPage, self).__init__(version, response) + 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, + ) - # Path Solution - self._solution = 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 get_instance(self, payload): + :returns: The updated FlexFlowInstance """ - Build an instance of 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 dict payload: Payload response from the API + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the FlexFlowInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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, + ) - :returns: twilio.rest.flex_api.v1.flex_flow.FlexFlowInstance - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowInstance - """ - return FlexFlowInstance(self._version, payload, ) + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FlexFlowInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, + ) - def __repr__(self): + 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 FlexFlowContext(InstanceContext): - """ """ - def __init__(self, version, sid): + def __init__(self, version: Version, sid: str): """ Initialize the FlexFlowContext - :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 + :param version: Version that contains the resource + :param sid: The SID of the Flex Flow resource to update. """ - super(FlexFlowContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'sid': sid, } - self._uri = '/FlexFlows/{sid}'.format(**self._solution) + self._solution = { + "sid": sid, + } + self._uri = "/FlexFlows/{sid}".format(**self._solution) - def fetch(self): + def _delete(self) -> tuple: """ - Fetch the FlexFlowInstance + Internal helper for delete operation - :returns: The fetched FlexFlowInstance - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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): - """ - Update the FlexFlowInstance + headers = values.of({}) - :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: Whether new channels created are long-lived - :param bool janitor_enabled: Boolean flag for enabling or disabling the Janitor - :param unicode integration_retry_count: The number of times to retry the webhook if the first attempt fails + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :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): + def delete(self) -> bool: """ Deletes the FlexFlowInstance + :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + success, _, _ = self._delete() + return success - def __repr__(self): + def delete_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Deletes the FlexFlowInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with success boolean, status code, and headers """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation -class FlexFlowInstance(InstanceResource): - """ """ + Returns: + tuple: (success_boolean, status_code, headers) + """ - class ChannelType(object): - WEB = "web" - SMS = "sms" - FACEBOOK = "facebook" - WHATSAPP = "whatsapp" - LINE = "line" - CUSTOM = "custom" + headers = values.of({}) - class IntegrationType(object): - STUDIO = "studio" - EXTERNAL = "external" - TASK = "task" + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - 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'), - } + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FlexFlowInstance - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): + :returns: True if delete succeeds, False otherwise """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + success, _, _ = await self._delete_async() + return success - :returns: FlexFlowContext for this FlexFlowInstance - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowContext + async def delete_with_http_info_async(self) -> ApiResponse: """ - if self._context is None: - self._context = FlexFlowContext(self._version, sid=self._solution['sid'], ) - return self._context + Asynchronous coroutine that deletes the FlexFlowInstance and return response metadata - @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 resource was created - :rtype: datetime + :returns: ApiResponse with success boolean, status code, and headers """ - return self._properties['date_created'] + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + def _fetch(self) -> tuple: """ - return self._properties['date_updated'] + Internal helper for fetch operation - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + Returns: + tuple: (payload, status_code, headers) """ - 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'] + headers = values.of({}) - @property - def chat_service_sid(self): - """ - :returns: The SID of the chat service - :rtype: unicode - """ - return self._properties['chat_service_sid'] + headers["Accept"] = "application/json" - @property - def channel_type(self): - """ - :returns: The channel type - :rtype: FlexFlowInstance.ChannelType - """ - return self._properties['channel_type'] + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - @property - def contact_identity(self): - """ - :returns: The channel contact's Identity - :rtype: unicode + def fetch(self) -> FlexFlowInstance: """ - return self._properties['contact_identity'] + Fetch the FlexFlowInstance - @property - def enabled(self): - """ - :returns: Whether the FlexFlow is enabled - :rtype: bool - """ - return self._properties['enabled'] - @property - def integration_type(self): - """ - :returns: The integration type - :rtype: FlexFlowInstance.IntegrationType + :returns: The fetched FlexFlowInstance """ - return self._properties['integration_type'] + payload, _, _ = self._fetch() + return FlexFlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - @property - def integration(self): - """ - :returns: An object that contains specific parameters for the integration - :rtype: dict + def fetch_with_http_info(self) -> ApiResponse: """ - return self._properties['integration'] + Fetch the FlexFlowInstance and return response metadata - @property - def long_lived(self): - """ - :returns: Whether new channels are long-lived - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['long_lived'] + payload, status_code, headers = self._fetch() + instance = FlexFlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def janitor_enabled(self): + async def _fetch_async(self) -> tuple: """ - :returns: Boolean flag for enabling or disabling the Janitor - :rtype: bool + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['janitor_enabled'] - @property - def url(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> FlexFlowInstance: """ - :returns: The absolute URL of the FlexFlow resource - :rtype: unicode + Asynchronous coroutine to fetch the FlexFlowInstance + + + :returns: The fetched FlexFlowInstance """ - return self._properties['url'] + payload, _, _ = await self._fetch_async() + return FlexFlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Fetch the FlexFlowInstance + Asynchronous coroutine to fetch the FlexFlowInstance and return response metadata - :returns: The fetched FlexFlowInstance - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowInstance + + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.fetch() + payload, status_code, headers = await self._fetch_async() + instance = FlexFlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChatServiceSid": chat_service_sid, + "ChannelType": channel_type, + "ContactIdentity": contact_identity, + "Enabled": serialize.boolean_to_string(enabled), + "IntegrationType": integration_type, + "Integration.FlowSid": integration_flow_sid, + "Integration.Url": integration_url, + "Integration.WorkspaceSid": integration_workspace_sid, + "Integration.WorkflowSid": integration_workflow_sid, + "Integration.Channel": integration_channel, + "Integration.Timeout": integration_timeout, + "Integration.Priority": integration_priority, + "Integration.CreationOnMessage": serialize.boolean_to_string( + integration_creation_on_message + ), + "LongLived": serialize.boolean_to_string(long_lived), + "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), + "Integration.RetryCount": integration_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - 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: Whether new channels created are long-lived - :param bool janitor_enabled: Boolean flag for enabling or disabling the Janitor - :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 """ - return self._proxy.update( + payload, _, _ = self._update( friendly_name=friendly_name, chat_service_sid=chat_service_sid, channel_type=channel_type, @@ -590,22 +747,1124 @@ def update(self, friendly_name=values.unset, chat_service_sid=values.unset, janitor_enabled=janitor_enabled, integration_retry_count=integration_retry_count, ) + return FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the FlexFlowInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChatServiceSid": chat_service_sid, + "ChannelType": channel_type, + "ContactIdentity": contact_identity, + "Enabled": serialize.boolean_to_string(enabled), + "IntegrationType": integration_type, + "Integration.FlowSid": integration_flow_sid, + "Integration.Url": integration_url, + "Integration.WorkspaceSid": integration_workspace_sid, + "Integration.WorkflowSid": integration_workflow_sid, + "Integration.Channel": integration_channel, + "Integration.Timeout": integration_timeout, + "Integration.Priority": integration_priority, + "Integration.CreationOnMessage": serialize.boolean_to_string( + integration_creation_on_message + ), + "LongLived": serialize.boolean_to_string(long_lived), + "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), + "Integration.RetryCount": integration_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> FlexFlowInstance: + """ + Asynchronous coroutine to update the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The updated FlexFlowInstance + """ + payload, _, _ = await self._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, + ) + return FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FlexFlowInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, 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 FlexFlowPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FlexFlowInstance: + """ + Build an instance of FlexFlowInstance + + :param payload: Payload response from the API + """ + + return FlexFlowInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class FlexFlowList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FlexFlowList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/FlexFlows" + + def _create( + self, + friendly_name: str, + chat_service_sid: str, + channel_type: "FlexFlowInstance.ChannelType", + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + chat_service_sid: str, + channel_type: "FlexFlowInstance.ChannelType", + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> FlexFlowInstance: + """ + Create the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The created FlexFlowInstance + """ + payload, _, _ = self._create( + 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 FlexFlowInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the FlexFlowInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + 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, + ) + instance = FlexFlowInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_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, + ) + return FlexFlowInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the FlexFlowInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_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, + ) + instance = FlexFlowInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FlexFlowInstance]: + """ + Streams FlexFlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FlexFlowInstance]: + """ + Asynchronously streams FlexFlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams FlexFlowInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams FlexFlowInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlexFlowInstance]: + """ + Lists FlexFlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlexFlowInstance]: + """ + Asynchronously lists FlexFlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists FlexFlowInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists FlexFlowInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlexFlowPage: + """ + Retrieve a single page of FlexFlowInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlexFlowInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlexFlowPage(self._version, response) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlexFlowPage: + """ + Asynchronously retrieve a single page of FlexFlowInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlexFlowInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlexFlowPage(self._version, response) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with FlexFlowPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FlexFlowPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with FlexFlowPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FlexFlowPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> FlexFlowPage: + """ + Retrieve a specific page of FlexFlowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlexFlowInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FlexFlowPage(self._version, response) + + async def get_page_async(self, target_url: str) -> FlexFlowPage: + """ + Asynchronously retrieve a specific page of FlexFlowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlexFlowInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FlexFlowPage(self._version, response) + + def get(self, sid: str) -> FlexFlowContext: + """ + Constructs a FlexFlowContext + + :param sid: The SID of the Flex Flow resource to update. + """ + return FlexFlowContext(self._version, sid=sid) + + def __call__(self, sid: str) -> FlexFlowContext: + """ + Constructs a FlexFlowContext + + :param sid: The SID of the Flex Flow resource to update. + """ + return FlexFlowContext(self._version, sid=sid) - def delete(self): - """ - Deletes the FlexFlowInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..0f48ce1cc5 --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_assessments_comment.py @@ -0,0 +1,829 @@ +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.api_response import ApiResponse + +from twilio.base.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[str] = payload.get("offset") + self.report: Optional[bool] = payload.get("report") + self.weight: Optional[str] = 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[str] = 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + category_id=category_id, + category_name=category_name, + comment=comment, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + authorization=authorization, + ) + return InsightsAssessmentsCommentInstance(self._version, payload) + + def create_with_http_info( + self, + category_id: str, + category_name: str, + comment: str, + segment_id: str, + agent_id: str, + offset: float, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the InsightsAssessmentsCommentInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + category_id=category_id, + category_name=category_name, + comment=comment, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + authorization=authorization, + ) + instance = InsightsAssessmentsCommentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + category_id=category_id, + category_name=category_name, + comment=comment, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + authorization=authorization, + ) + return InsightsAssessmentsCommentInstance(self._version, payload) + + async def create_with_http_info_async( + self, + category_id: str, + category_name: str, + comment: str, + segment_id: str, + agent_id: str, + offset: float, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the InsightsAssessmentsCommentInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + category_id=category_id, + category_name=category_name, + comment=comment, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + authorization=authorization, + ) + instance = InsightsAssessmentsCommentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams InsightsAssessmentsCommentInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams InsightsAssessmentsCommentInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists InsightsAssessmentsCommentInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists InsightsAssessmentsCommentInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with InsightsAssessmentsCommentPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InsightsAssessmentsCommentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with InsightsAssessmentsCommentPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InsightsAssessmentsCommentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..c407089755 --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_conversations.py @@ -0,0 +1,555 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsConversationsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InsightsConversationsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsConversationsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InsightsConversationsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with InsightsConversationsPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InsightsConversationsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with InsightsConversationsPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InsightsConversationsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..3ecf2f8156 --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_questionnaires.py @@ -0,0 +1,1462 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + authorization=authorization, + ) + + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsQuestionnairesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + authorization=authorization, + ) + + async def fetch_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InsightsQuestionnairesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the InsightsQuestionnairesInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + 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 + """ + success, _, _ = self._delete(authorization=authorization) + return success + + def delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(authorization=authorization) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async(authorization=authorization) + return success + + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + authorization=authorization + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self, authorization: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", 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 + """ + payload, _, _ = self._fetch(authorization=authorization) + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsQuestionnairesInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(authorization=authorization) + instance = InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(authorization=authorization) + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + + async def fetch_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InsightsQuestionnairesInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + authorization=authorization + ) + instance = InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the InsightsQuestionnairesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + instance = InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + instance = InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + name=name, + authorization=authorization, + description=description, + active=active, + question_sids=question_sids, + ) + return InsightsQuestionnairesInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the InsightsQuestionnairesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + name=name, + authorization=authorization, + description=description, + active=active, + question_sids=question_sids, + ) + instance = InsightsQuestionnairesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + name=name, + authorization=authorization, + description=description, + active=active, + question_sids=question_sids, + ) + return InsightsQuestionnairesInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the InsightsQuestionnairesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + name=name, + authorization=authorization, + description=description, + active=active, + question_sids=question_sids, + ) + instance = InsightsQuestionnairesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsQuestionnairesInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + include_inactive=include_inactive, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InsightsQuestionnairesInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + include_inactive=include_inactive, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsQuestionnairesInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + include_inactive=include_inactive, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InsightsQuestionnairesInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + include_inactive=include_inactive, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with InsightsQuestionnairesPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InsightsQuestionnairesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with InsightsQuestionnairesPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InsightsQuestionnairesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..9cc42e866a --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_questionnaires_category.py @@ -0,0 +1,1058 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesCategoryInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + authorization=authorization, + ) + + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesCategoryInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 update_with_http_info( + self, name: str, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the InsightsQuestionnairesCategoryInstance with HTTP info + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + name=name, + authorization=authorization, + ) + + async def update_with_http_info_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesCategoryInstance with HTTP info + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + 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 + """ + success, _, _ = self._delete(authorization=authorization) + return success + + def delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesCategoryInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(authorization=authorization) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async(authorization=authorization) + return success + + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesCategoryInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + authorization=authorization + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _update( + self, name: str, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, 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 + """ + payload, _, _ = self._update(name=name, authorization=authorization) + return InsightsQuestionnairesCategoryInstance( + self._version, payload, category_sid=self._solution["category_sid"] + ) + + def update_with_http_info( + self, name: str, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the InsightsQuestionnairesCategoryInstance and return response metadata + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + name=name, authorization=authorization + ) + instance = InsightsQuestionnairesCategoryInstance( + self._version, payload, category_sid=self._solution["category_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(name=name, authorization=authorization) + return InsightsQuestionnairesCategoryInstance( + self._version, payload, category_sid=self._solution["category_sid"] + ) + + async def update_with_http_info_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesCategoryInstance and return response metadata + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + name=name, authorization=authorization + ) + instance = InsightsQuestionnairesCategoryInstance( + self._version, payload, category_sid=self._solution["category_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(name=name, authorization=authorization) + return InsightsQuestionnairesCategoryInstance(self._version, payload) + + def create_with_http_info( + self, name: str, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the InsightsQuestionnairesCategoryInstance and return response metadata + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + name=name, authorization=authorization + ) + instance = InsightsQuestionnairesCategoryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(name=name, authorization=authorization) + return InsightsQuestionnairesCategoryInstance(self._version, payload) + + async def create_with_http_info_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the InsightsQuestionnairesCategoryInstance and return response metadata + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + name=name, authorization=authorization + ) + instance = InsightsQuestionnairesCategoryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsQuestionnairesCategoryInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InsightsQuestionnairesCategoryInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsQuestionnairesCategoryInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InsightsQuestionnairesCategoryInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with InsightsQuestionnairesCategoryPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InsightsQuestionnairesCategoryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with InsightsQuestionnairesCategoryPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InsightsQuestionnairesCategoryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..e8a88190b6 --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_questionnaires_question.py @@ -0,0 +1,1336 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesQuestionInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + authorization=authorization, + ) + + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesQuestionInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the InsightsQuestionnairesQuestionInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesQuestionInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + 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 + """ + success, _, _ = self._delete(authorization=authorization) + return success + + def delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesQuestionInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(authorization=authorization) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async(authorization=authorization) + return success + + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesQuestionInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + authorization=authorization + ) + return ApiResponse(data=success, status_code=status_code, 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, 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 + """ + payload, _, _ = self._update( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) + return InsightsQuestionnairesQuestionInstance( + self._version, payload, question_sid=self._solution["question_sid"] + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the InsightsQuestionnairesQuestionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) + instance = InsightsQuestionnairesQuestionInstance( + self._version, payload, question_sid=self._solution["question_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) + return InsightsQuestionnairesQuestionInstance( + self._version, payload, question_sid=self._solution["question_sid"] + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesQuestionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) + instance = InsightsQuestionnairesQuestionInstance( + self._version, payload, question_sid=self._solution["question_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + category_sid=category_sid, + question=question, + answer_set_id=answer_set_id, + allow_na=allow_na, + authorization=authorization, + description=description, + ) + return InsightsQuestionnairesQuestionInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the InsightsQuestionnairesQuestionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + category_sid=category_sid, + question=question, + answer_set_id=answer_set_id, + allow_na=allow_na, + authorization=authorization, + description=description, + ) + instance = InsightsQuestionnairesQuestionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + category_sid=category_sid, + question=question, + answer_set_id=answer_set_id, + allow_na=allow_na, + authorization=authorization, + description=description, + ) + return InsightsQuestionnairesQuestionInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the InsightsQuestionnairesQuestionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + category_sid=category_sid, + question=question, + answer_set_id=answer_set_id, + allow_na=allow_na, + authorization=authorization, + description=description, + ) + instance = InsightsQuestionnairesQuestionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsQuestionnairesQuestionInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + category_sid=category_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams InsightsQuestionnairesQuestionInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + category_sid=category_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsQuestionnairesQuestionInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + category_sid=category_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists InsightsQuestionnairesQuestionInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + category_sid=category_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with InsightsQuestionnairesQuestionPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InsightsQuestionnairesQuestionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with InsightsQuestionnairesQuestionPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InsightsQuestionnairesQuestionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..e5232a323a --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_segments.py @@ -0,0 +1,635 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams InsightsSegmentsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams InsightsSegmentsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists InsightsSegmentsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists InsightsSegmentsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with InsightsSegmentsPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InsightsSegmentsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with InsightsSegmentsPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InsightsSegmentsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..d633933625 --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_session.py @@ -0,0 +1,281 @@ +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.api_response import ApiResponse +from twilio.base.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 create_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the InsightsSessionInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + authorization=authorization, + ) + + async def create_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to create the InsightsSessionInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSessionInstance: + """ + Create the InsightsSessionInstance + + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsSessionInstance + """ + payload, _, _ = self._create(authorization=authorization) + return InsightsSessionInstance(self._version, payload) + + def create_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the InsightsSessionInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(authorization=authorization) + instance = InsightsSessionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(authorization=authorization) + return InsightsSessionInstance(self._version, payload) + + async def create_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to create the InsightsSessionInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + authorization=authorization + ) + instance = InsightsSessionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..8f6938ded8 --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_settings_answer_sets.py @@ -0,0 +1,167 @@ +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.api_response import ApiResponse + +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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSettingsAnswerSetsInstance: + """ + Fetch the InsightsSettingsAnswerSetsInstance + + :param authorization: The Authorization HTTP request header + :returns: The fetched InsightsSettingsAnswerSetsInstance + """ + payload, _, _ = self._fetch(authorization=authorization) + return InsightsSettingsAnswerSetsInstance(self._version, payload) + + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsSettingsAnswerSetsInstance and return response metadata + + :param authorization: The Authorization HTTP request header + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(authorization=authorization) + instance = InsightsSettingsAnswerSetsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(authorization=authorization) + return InsightsSettingsAnswerSetsInstance(self._version, payload) + + async def fetch_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously fetch the InsightsSettingsAnswerSetsInstance and return response metadata + + :param authorization: The Authorization HTTP request header + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + authorization=authorization + ) + instance = InsightsSettingsAnswerSetsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..44ca4f4d36 --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_settings_comment.py @@ -0,0 +1,161 @@ +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.api_response import ApiResponse + +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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSettingsCommentInstance: + """ + Fetch the InsightsSettingsCommentInstance + + :param authorization: The Authorization HTTP request header + :returns: The fetched InsightsSettingsCommentInstance + """ + payload, _, _ = self._fetch(authorization=authorization) + return InsightsSettingsCommentInstance(self._version, payload) + + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsSettingsCommentInstance and return response metadata + + :param authorization: The Authorization HTTP request header + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(authorization=authorization) + instance = InsightsSettingsCommentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(authorization=authorization) + return InsightsSettingsCommentInstance(self._version, payload) + + async def fetch_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously fetch the InsightsSettingsCommentInstance and return response metadata + + :param authorization: The Authorization HTTP request header + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + authorization=authorization + ) + instance = InsightsSettingsCommentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..33ef7c663a --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_user_roles.py @@ -0,0 +1,285 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsUserRolesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + authorization=authorization, + ) + + async def fetch_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InsightsUserRolesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch( + self, authorization: Union[str, object] = values.unset + ) -> InsightsUserRolesInstance: + """ + Fetch the InsightsUserRolesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsUserRolesInstance + """ + payload, _, _ = self._fetch(authorization=authorization) + return InsightsUserRolesInstance( + self._version, + payload, + ) + + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsUserRolesInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(authorization=authorization) + instance = InsightsUserRolesInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(authorization=authorization) + return InsightsUserRolesInstance( + self._version, + payload, + ) + + async def fetch_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InsightsUserRolesInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + authorization=authorization + ) + instance = InsightsUserRolesInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..9e63203161 --- /dev/null +++ b/twilio/rest/flex_api/v1/interaction/__init__.py @@ -0,0 +1,624 @@ +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.api_response import ApiResponse +from twilio.base.instance_context 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + self, webhook_ttid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the InteractionInstance with HTTP info + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + webhook_ttid=webhook_ttid, + ) + + async def update_with_http_info_async( + self, webhook_ttid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionInstance with HTTP info + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InteractionInstance: + """ + Fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + payload, _, _ = self._fetch() + return InteractionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InteractionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> InteractionInstance: + """ + Asynchronous coroutine to fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + payload, _, _ = await self._fetch_async() + return InteractionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InteractionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, webhook_ttid: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "WebhookTtid": webhook_ttid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(webhook_ttid=webhook_ttid) + return InteractionInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, webhook_ttid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the InteractionInstance and return response metadata + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(webhook_ttid=webhook_ttid) + instance = InteractionInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, webhook_ttid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "WebhookTtid": webhook_ttid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(webhook_ttid=webhook_ttid) + return InteractionInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, webhook_ttid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionInstance and return response metadata + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + webhook_ttid=webhook_ttid + ) + instance = InteractionInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + channel=channel, + routing=routing, + interaction_context_sid=interaction_context_sid, + webhook_ttid=webhook_ttid, + ) + return InteractionInstance(self._version, payload) + + def create_with_http_info( + self, + channel: object, + routing: Union[object, object] = values.unset, + interaction_context_sid: Union[str, object] = values.unset, + webhook_ttid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the InteractionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + channel=channel, + routing=routing, + interaction_context_sid=interaction_context_sid, + webhook_ttid=webhook_ttid, + ) + instance = InteractionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + channel=channel, + routing=routing, + interaction_context_sid=interaction_context_sid, + webhook_ttid=webhook_ttid, + ) + return InteractionInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the InteractionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + channel=channel, + routing=routing, + interaction_context_sid=interaction_context_sid, + webhook_ttid=webhook_ttid, + ) + instance = InteractionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..2c362c9dbd --- /dev/null +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py @@ -0,0 +1,995 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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" + PAUSE = "pause" + TRANSFER = "transfer" + + 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the InteractionChannelInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + routing=routing, + ) + + async def update_with_http_info_async( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionChannelInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InteractionChannelInstance: + """ + Fetch the InteractionChannelInstance + + + :returns: The fetched InteractionChannelInstance + """ + payload, _, _ = self._fetch() + return InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> InteractionChannelInstance: + """ + Asynchronous coroutine to fetch the InteractionChannelInstance + + + :returns: The fetched InteractionChannelInstance + """ + payload, _, _ = await self._fetch_async() + return InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + "Routing": serialize.object(routing), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(status=status, routing=routing) + return InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the InteractionChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status, routing=routing) + instance = InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + "Routing": serialize.object(routing), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(status=status, routing=routing) + return InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, routing=routing + ) + instance = InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InteractionChannelInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InteractionChannelInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InteractionChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InteractionChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InteractionChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InteractionChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..b34035b6b2 --- /dev/null +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_invite.py @@ -0,0 +1,608 @@ +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.api_response import ApiResponse + +from twilio.base.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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, routing: object) -> InteractionChannelInviteInstance: + """ + Create the InteractionChannelInviteInstance + + :param routing: The Interaction's routing logic. + + :returns: The created InteractionChannelInviteInstance + """ + payload, _, _ = self._create(routing=routing) + return InteractionChannelInviteInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def create_with_http_info(self, routing: object) -> ApiResponse: + """ + Create the InteractionChannelInviteInstance and return response metadata + + :param routing: The Interaction's routing logic. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(routing=routing) + instance = InteractionChannelInviteInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, routing: object) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, routing: object) -> InteractionChannelInviteInstance: + """ + Asynchronously create the InteractionChannelInviteInstance + + :param routing: The Interaction's routing logic. + + :returns: The created InteractionChannelInviteInstance + """ + payload, _, _ = await self._create_async(routing=routing) + return InteractionChannelInviteInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_with_http_info_async(self, routing: object) -> ApiResponse: + """ + Asynchronously create the InteractionChannelInviteInstance and return response metadata + + :param routing: The Interaction's routing logic. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(routing=routing) + instance = InteractionChannelInviteInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InteractionChannelInviteInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InteractionChannelInviteInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InteractionChannelInviteInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InteractionChannelInviteInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution + ) + + async def 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, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionChannelInvitePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InteractionChannelInvitePage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionChannelInvitePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InteractionChannelInvitePage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..9be568cea4 --- /dev/null +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_participant.py @@ -0,0 +1,954 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 update_with_http_info( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> ApiResponse: + """ + Update the InteractionChannelParticipantInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionChannelParticipantInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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") -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> InteractionChannelParticipantInstance: + """ + Update the InteractionChannelParticipantInstance + + :param status: + + :returns: The updated InteractionChannelParticipantInstance + """ + payload, _, _ = self._update(status=status) + return InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> ApiResponse: + """ + Update the InteractionChannelParticipantInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> InteractionChannelParticipantInstance: + """ + Asynchronous coroutine to update the InteractionChannelParticipantInstance + + :param status: + + :returns: The updated InteractionChannelParticipantInstance + """ + payload, _, _ = await self._update_async(status=status) + return InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionChannelParticipantInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + type=type, + media_properties=media_properties, + routing_properties=routing_properties, + ) + return InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def create_with_http_info( + self, + type: "InteractionChannelParticipantInstance.Type", + media_properties: object, + routing_properties: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Create the InteractionChannelParticipantInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + media_properties=media_properties, + routing_properties=routing_properties, + ) + instance = InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "InteractionChannelParticipantInstance.Type", + media_properties: object, + routing_properties: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + type=type, + media_properties=media_properties, + routing_properties=routing_properties, + ) + return InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_with_http_info_async( + self, + type: "InteractionChannelParticipantInstance.Type", + media_properties: object, + routing_properties: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the InteractionChannelParticipantInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + media_properties=media_properties, + routing_properties=routing_properties, + ) + instance = InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InteractionChannelParticipantInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InteractionChannelParticipantInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InteractionChannelParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InteractionChannelParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution + ) + + async def 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, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionChannelParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InteractionChannelParticipantPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionChannelParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InteractionChannelParticipantPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..13f59fadbc --- /dev/null +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_transfer.py @@ -0,0 +1,633 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionTransferInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionTransferInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Update the InteractionTransferInstance with HTTP info + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + body=body, + ) + + async def update_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionTransferInstance with HTTP info + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InteractionTransferInstance: + """ + Fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + payload, _, _ = self._fetch() + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionTransferInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> InteractionTransferInstance: + """ + Asynchronous coroutine to fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + payload, _, _ = await self._fetch_async() + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionTransferInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + payload, _, _ = self._update(body=body) + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Update the InteractionTransferInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(body=body) + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Asynchronous coroutine to update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + payload, _, _ = await self._update_async(body=body) + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionTransferInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(body=body) + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Create the InteractionTransferInstance + + :param body: + + :returns: The created InteractionTransferInstance + """ + payload, _, _ = self._create(body=body) + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def create_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the InteractionTransferInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body) + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Asynchronously create the InteractionTransferInstance + + :param body: + + :returns: The created InteractionTransferInstance + """ + payload, _, _ = await self._create_async(body=body) + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the InteractionTransferInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(body=body) + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..5765f3478d --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin/__init__.py @@ -0,0 +1,1206 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + flex_metadata=flex_metadata, + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the PluginInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + + async def update_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + 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 + """ + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(flex_metadata=flex_metadata) + instance = PluginInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return PluginInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + flex_metadata=flex_metadata + ) + instance = PluginInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + return PluginInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the PluginInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + instance = PluginInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + return PluginInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + instance = PluginInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + unique_name=unique_name, + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + return PluginInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: str, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the PluginInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + instance = PluginInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + return PluginInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the PluginInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + instance = PluginInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PluginInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PluginInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PluginInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PluginInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with PluginPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PluginPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with PluginPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PluginPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..acd3330caa --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin/plugin_versions.py @@ -0,0 +1,1025 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginVersionsInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + flex_metadata=flex_metadata, + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginVersionsInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + 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 + """ + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginVersionsInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginVersionsInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(flex_metadata=flex_metadata) + instance = PluginVersionsInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return PluginVersionsInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginVersionsInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + flex_metadata=flex_metadata + ) + instance = PluginVersionsInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + resource_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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Version": resource_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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + resource_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 resource_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 + """ + payload, _, _ = self._create( + resource_version=resource_version, + plugin_url=plugin_url, + flex_metadata=flex_metadata, + changelog=changelog, + private=private, + cli_version=cli_version, + validate_status=validate_status, + ) + return PluginVersionsInstance( + self._version, payload, plugin_sid=self._solution["plugin_sid"] + ) + + def create_with_http_info( + self, + resource_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, + ) -> ApiResponse: + """ + Create the PluginVersionsInstance and return response metadata + + :param resource_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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + resource_version=resource_version, + plugin_url=plugin_url, + flex_metadata=flex_metadata, + changelog=changelog, + private=private, + cli_version=cli_version, + validate_status=validate_status, + ) + instance = PluginVersionsInstance( + self._version, payload, plugin_sid=self._solution["plugin_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + resource_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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Version": resource_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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + resource_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 resource_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 + """ + payload, _, _ = await self._create_async( + resource_version=resource_version, + plugin_url=plugin_url, + flex_metadata=flex_metadata, + changelog=changelog, + private=private, + cli_version=cli_version, + validate_status=validate_status, + ) + return PluginVersionsInstance( + self._version, payload, plugin_sid=self._solution["plugin_sid"] + ) + + async def create_with_http_info_async( + self, + resource_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, + ) -> ApiResponse: + """ + Asynchronously create the PluginVersionsInstance and return response metadata + + :param resource_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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + resource_version=resource_version, + plugin_url=plugin_url, + flex_metadata=flex_metadata, + changelog=changelog, + private=private, + cli_version=cli_version, + validate_status=validate_status, + ) + instance = PluginVersionsInstance( + self._version, payload, plugin_sid=self._solution["plugin_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PluginVersionsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PluginVersionsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PluginVersionsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PluginVersionsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with PluginVersionsPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PluginVersionsPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with PluginVersionsPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PluginVersionsPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..7dbb89ffdc --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_archive.py @@ -0,0 +1,312 @@ +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.api_response import ApiResponse +from twilio.base.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 update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PluginArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + flex_metadata=flex_metadata, + ) + + async def update_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(flex_metadata=flex_metadata) + return PluginArchiveInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PluginArchiveInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(flex_metadata=flex_metadata) + instance = PluginArchiveInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(flex_metadata=flex_metadata) + return PluginArchiveInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginArchiveInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + flex_metadata=flex_metadata + ) + instance = PluginArchiveInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..d98e1f3615 --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_configuration/__init__.py @@ -0,0 +1,960 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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, + ) + + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginConfigurationInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + flex_metadata=flex_metadata, + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginConfigurationInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + 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 + """ + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginConfigurationInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(flex_metadata=flex_metadata) + instance = PluginConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return PluginConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginConfigurationInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + flex_metadata=flex_metadata + ) + instance = PluginConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + name=name, + flex_metadata=flex_metadata, + plugins=plugins, + description=description, + ) + return PluginConfigurationInstance(self._version, payload) + + def create_with_http_info( + self, + name: str, + flex_metadata: Union[str, object] = values.unset, + plugins: Union[List[object], object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the PluginConfigurationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + name=name, + flex_metadata=flex_metadata, + plugins=plugins, + description=description, + ) + instance = PluginConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + name=name, + flex_metadata=flex_metadata, + plugins=plugins, + description=description, + ) + return PluginConfigurationInstance(self._version, payload) + + async def create_with_http_info_async( + self, + name: str, + flex_metadata: Union[str, object] = values.unset, + plugins: Union[List[object], object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the PluginConfigurationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + name=name, + flex_metadata=flex_metadata, + plugins=plugins, + description=description, + ) + instance = PluginConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PluginConfigurationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PluginConfigurationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PluginConfigurationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PluginConfigurationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with PluginConfigurationPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PluginConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with PluginConfigurationPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PluginConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..473f86f966 --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.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 datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the ConfiguredPluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + flex_metadata=flex_metadata, + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfiguredPluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + 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 + """ + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], + ) + + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the ConfiguredPluginInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(flex_metadata=flex_metadata) + instance = ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfiguredPluginInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + flex_metadata=flex_metadata + ) + instance = ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConfiguredPluginInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConfiguredPluginInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConfiguredPluginInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConfiguredPluginInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ConfiguredPluginPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConfiguredPluginPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ConfiguredPluginPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConfiguredPluginPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..e880c68ec4 --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_configuration_archive.py @@ -0,0 +1,316 @@ +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.api_response import ApiResponse +from twilio.base.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 update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PluginConfigurationArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + flex_metadata=flex_metadata, + ) + + async def update_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginConfigurationArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(flex_metadata=flex_metadata) + return PluginConfigurationArchiveInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PluginConfigurationArchiveInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(flex_metadata=flex_metadata) + instance = PluginConfigurationArchiveInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(flex_metadata=flex_metadata) + return PluginConfigurationArchiveInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginConfigurationArchiveInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + flex_metadata=flex_metadata + ) + instance = PluginConfigurationArchiveInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..08d3bbd00f --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_release.py @@ -0,0 +1,882 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginReleaseInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + flex_metadata=flex_metadata, + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginReleaseInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + 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 + """ + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginReleaseInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginReleaseInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(flex_metadata=flex_metadata) + instance = PluginReleaseInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return PluginReleaseInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginReleaseInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + flex_metadata=flex_metadata + ) + instance = PluginReleaseInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + configuration_id=configuration_id, flex_metadata=flex_metadata + ) + return PluginReleaseInstance(self._version, payload) + + def create_with_http_info( + self, configuration_id: str, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the PluginReleaseInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + configuration_id=configuration_id, flex_metadata=flex_metadata + ) + instance = PluginReleaseInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, configuration_id: str, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + configuration_id=configuration_id, flex_metadata=flex_metadata + ) + return PluginReleaseInstance(self._version, payload) + + async def create_with_http_info_async( + self, configuration_id: str, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the PluginReleaseInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + configuration_id=configuration_id, flex_metadata=flex_metadata + ) + instance = PluginReleaseInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PluginReleaseInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PluginReleaseInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PluginReleaseInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PluginReleaseInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with PluginReleasePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PluginReleasePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with PluginReleasePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PluginReleasePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..d2b601a828 --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_version_archive.py @@ -0,0 +1,344 @@ +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.api_response import ApiResponse +from twilio.base.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 update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PluginVersionArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + flex_metadata=flex_metadata, + ) + + async def update_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginVersionArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(flex_metadata=flex_metadata) + return PluginVersionArchiveInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PluginVersionArchiveInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(flex_metadata=flex_metadata) + instance = PluginVersionArchiveInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(flex_metadata=flex_metadata) + return PluginVersionArchiveInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginVersionArchiveInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + flex_metadata=flex_metadata + ) + instance = PluginVersionArchiveInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..a13a1baab7 --- /dev/null +++ b/twilio/rest/flex_api/v1/provisioning_status.py @@ -0,0 +1,246 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ProvisioningStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ProvisioningStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ProvisioningStatusInstance: + """ + Fetch the ProvisioningStatusInstance + + + :returns: The fetched ProvisioningStatusInstance + """ + payload, _, _ = self._fetch() + return ProvisioningStatusInstance( + self._version, + payload, + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ProvisioningStatusInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ProvisioningStatusInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ProvisioningStatusInstance: + """ + Asynchronous coroutine to fetch the ProvisioningStatusInstance + + + :returns: The fetched ProvisioningStatusInstance + """ + payload, _, _ = await self._fetch_async() + return ProvisioningStatusInstance( + self._version, + payload, + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ProvisioningStatusInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ProvisioningStatusInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 54a5def292..0b0560cb89 100644 --- a/twilio/rest/flex_api/v1/web_channel.py +++ b/twilio/rest/flex_api/v1/web_channel.py @@ -1,406 +1,1164 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + + class ChatStatus(object): + INACTIVE = "inactive" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the WebChannel resource and owns this Workflow. + :ivar flex_flow_sid: The SID of the Flex Flow. + :ivar sid: The unique string that we created to identify the WebChannel resource. + :ivar url: The absolute URL of the WebChannel resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.flex_flow_sid: Optional[str] = payload.get("flex_flow_sid") + self.sid: Optional[str] = payload.get("sid") + self.url: Optional[str] = payload.get("url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "sid": sid or self.sid, + } - def __init__(self, version): + self._context: Optional[WebChannelContext] = None + + @property + def _proxy(self) -> "WebChannelContext": """ - Initialize the WebChannelList + 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: WebChannelContext for this WebChannelInstance + """ + if self._context is None: + self._context = WebChannelContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.flex_api.v1.web_channel.WebChannelList - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelList + def delete(self) -> bool: """ - super(WebChannelList, self).__init__(version) + Deletes the WebChannelInstance - # Path Solution - self._solution = {} - self._uri = '/WebChannels'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + 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 WebChannelInstance - :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 await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebChannelInstance with HTTP info - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() - def list(self, limit=None, page_size=None): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Lists WebChannelInstance 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 WebChannelInstance with HTTP info - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "WebChannelInstance": """ - Retrieve a single page of WebChannelInstance records from the API. - Request is executed immediately + 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 self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "WebChannelInstance": + """ + Asynchronous coroutine to fetch the WebChannelInstance - return WebChannelPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched WebChannelInstance """ - Retrieve a specific page of WebChannelInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebChannelInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelPage + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebChannelInstance with HTTP info - return WebChannelPage(self._version, response, self._solution) - def create(self, flex_flow_sid, identity, customer_friendly_name, - chat_friendly_name, chat_unique_name=values.unset, - pre_engagement_data=values.unset): + :returns: ApiResponse with instance, status code, and headers """ - Create the WebChannelInstance + return await self._proxy.fetch_with_http_info_async() - :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 + def update( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> "WebChannelInstance": + """ + Update the WebChannelInstance - :returns: The created WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelInstance + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: The updated 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, - }) + return self._proxy.update( + chat_status=chat_status, + post_engagement_data=post_engagement_data, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def update_async( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> "WebChannelInstance": + """ + Asynchronous coroutine to update the WebChannelInstance - return WebChannelInstance(self._version, payload, ) + :param chat_status: + :param post_engagement_data: The post-engagement data. - def get(self, sid): + :returns: The updated WebChannelInstance """ - Constructs a WebChannelContext + return await self._proxy.update_async( + chat_status=chat_status, + post_engagement_data=post_engagement_data, + ) - :param sid: The SID of the WebChannel resource to fetch + def update_with_http_info( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the WebChannelInstance with HTTP info - :returns: twilio.rest.flex_api.v1.web_channel.WebChannelContext - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelContext + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: ApiResponse with instance, status code, and headers """ - return WebChannelContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + chat_status=chat_status, + post_engagement_data=post_engagement_data, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Constructs a WebChannelContext + Asynchronous coroutine to update the WebChannelInstance with HTTP info - :param sid: The SID of the WebChannel resource to fetch + :param chat_status: + :param post_engagement_data: The post-engagement data. - :returns: twilio.rest.flex_api.v1.web_channel.WebChannelContext - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelContext + :returns: ApiResponse with instance, status code, and headers """ - return WebChannelContext(self._version, sid=sid, ) + return await self._proxy.update_with_http_info_async( + chat_status=chat_status, + post_engagement_data=post_engagement_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 WebChannelPage(Page): - """ """ +class WebChannelContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the WebChannelPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the WebChannelContext - :returns: twilio.rest.flex_api.v1.web_channel.WebChannelPage - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelPage + :param version: Version that contains the resource + :param sid: The SID of the WebChannel resource to update. """ - super(WebChannelPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/WebChannels/{sid}".format(**self._solution) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of WebChannelInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.flex_api.v1.web_channel.WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelInstance + def delete(self) -> bool: """ - return WebChannelInstance(self._version, payload, ) + Deletes the WebChannelInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the WebChannelInstance and return response metadata -class WebChannelContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: """ - Initialize the WebChannelContext + Internal async helper for delete operation - :param Version version: Version that contains the resource - :param sid: The SID of the WebChannel resource to fetch + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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: """ - super(WebChannelContext, self).__init__(version) + Asynchronous coroutine that deletes the WebChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebChannelInstance and return response metadata - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/WebChannels/{sid}'.format(**self._solution) - def fetch(self): + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> 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, ) + payload, _, _ = self._fetch() + return WebChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - return WebChannelInstance(self._version, payload, sid=self._solution['sid'], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" - def update(self, chat_status=values.unset, post_engagement_data=values.unset): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> WebChannelInstance: + """ + Asynchronous coroutine to fetch the WebChannelInstance + + + :returns: The fetched WebChannelInstance + """ + payload, _, _ = await self._fetch_async() + return WebChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ChatStatus": chat_status, + "PostEngagementData": post_engagement_data, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelInstance: """ 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._update( + chat_status=chat_status, post_engagement_data=post_engagement_data + ) + return WebChannelInstance(self._version, payload, sid=self._solution["sid"]) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def update_with_http_info( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the WebChannelInstance and return response metadata - return WebChannelInstance(self._version, payload, sid=self._solution['sid'], ) + :param chat_status: + :param post_engagement_data: The post-engagement data. - def delete(self): + :returns: ApiResponse with instance, status code, and headers """ - Deletes the WebChannelInstance + payload, status_code, headers = self._update( + chat_status=chat_status, post_engagement_data=post_engagement_data + ) + instance = WebChannelInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation - :returns: True if delete succeeds, False otherwise - :rtype: bool + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ChatStatus": chat_status, + "PostEngagementData": post_engagement_data, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelInstance: + """ + Asynchronous coroutine to update the WebChannelInstance + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: The updated WebChannelInstance + """ + payload, _, _ = await self._update_async( + chat_status=chat_status, post_engagement_data=post_engagement_data + ) + return WebChannelInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebChannelInstance and return response metadata + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._update_async( + chat_status=chat_status, post_engagement_data=post_engagement_data + ) + instance = WebChannelInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 WebChannelInstance(InstanceResource): - """ """ +class WebChannelPage(Page): - class ChatStatus(object): - INACTIVE = "inactive" + def get_instance(self, payload: Dict[str, Any]) -> WebChannelInstance: + """ + Build an instance of WebChannelInstance - def __init__(self, version, payload, sid=None): + :param payload: Payload response from the API """ - Initialize the WebChannelInstance - :returns: twilio.rest.flex_api.v1.web_channel.WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelInstance + return WebChannelInstance(self._version, payload) + + def __repr__(self) -> str: """ - super(WebChannelInstance, self).__init__(version) + Provide a friendly representation - # 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')), - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): +class WebChannelList(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 WebChannelList + + :param version: Version that contains the resource - :returns: WebChannelContext for this WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelContext """ - if self._context is None: - self._context = WebChannelContext(self._version, sid=self._solution['sid'], ) - return self._context + super().__init__(version) + + self._uri = "/WebChannels" + + def _create( + self, + flex_flow_sid: str, + identity: str, + customer_friendly_name: str, + chat_friendly_name: str, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation - @property - def account_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the Account that created the resource and owns this Workflow - :rtype: unicode + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._properties['account_sid'] + Create the WebChannelInstance - @property - def flex_flow_sid(self): + :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 """ - :returns: The SID of the FlexFlow - :rtype: unicode + payload, _, _ = self._create( + flex_flow_sid=flex_flow_sid, + identity=identity, + customer_friendly_name=customer_friendly_name, + chat_friendly_name=chat_friendly_name, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + ) + return WebChannelInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['flex_flow_sid'] + Create the WebChannelInstance and return response metadata - @property - def sid(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The unique string that identifies the WebChannel resource - :rtype: unicode + payload, status_code, headers = self._create( + flex_flow_sid=flex_flow_sid, + identity=identity, + customer_friendly_name=customer_friendly_name, + chat_friendly_name=chat_friendly_name, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + ) + instance = WebChannelInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: """ - return self._properties['sid'] + Internal async helper for create operation - @property - def url(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The absolute URL of the WebChannel resource - :rtype: unicode + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._properties['url'] + Asynchronously create the WebChannelInstance - @property - def date_created(self): + :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 """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + payload, _, _ = await self._create_async( + flex_flow_sid=flex_flow_sid, + identity=identity, + customer_friendly_name=customer_friendly_name, + chat_friendly_name=chat_friendly_name, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + ) + return WebChannelInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['date_created'] + Asynchronously create the WebChannelInstance and return response metadata - @property - def date_updated(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + payload, status_code, headers = await self._create_async( + flex_flow_sid=flex_flow_sid, + identity=identity, + customer_friendly_name=customer_friendly_name, + chat_friendly_name=chat_friendly_name, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + ) + instance = WebChannelInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebChannelInstance]: """ - return self._properties['date_updated'] + 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. - 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 WebChannelInstance + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :returns: The fetched WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelInstance + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WebChannelInstance]: """ - return self._proxy.fetch() + 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) - def update(self, chat_status=values.unset, post_engagement_data=values.unset): + :returns: Generator that will yield up to limit results """ - Update the WebChannelInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :param WebChannelInstance.ChatStatus chat_status: The chat status - :param unicode post_engagement_data: The post-engagement data + return self._version.stream_async(page, limits["limit"]) - :returns: The updated WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelInstance + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams WebChannelInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._proxy.update(chat_status=chat_status, post_engagement_data=post_engagement_data, ) + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - def delete(self): + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Deletes the WebChannelInstance + Asynchronously streams WebChannelInstance and returns headers from first page - :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._proxy.delete() + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebChannelInstance]: + """ + Lists WebChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebChannelInstance]: + """ + Asynchronously lists WebChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists WebChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists WebChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebChannelPage: + """ + Retrieve a single page of WebChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebChannelPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebChannelPage: + """ + Asynchronously retrieve a single page of WebChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebChannelPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WebChannelPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WebChannelPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> WebChannelPage: + """ + Retrieve a specific page of WebChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WebChannelPage(self._version, response) + + async def get_page_async(self, target_url: str) -> WebChannelPage: + """ + Asynchronously retrieve a specific page of WebChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebChannelPage(self._version, response) + + def get(self, sid: str) -> WebChannelContext: + """ + Constructs a WebChannelContext + + :param sid: The SID of the WebChannel resource to update. + """ + return WebChannelContext(self._version, sid=sid) + + def __call__(self, sid: str) -> WebChannelContext: + """ + Constructs a WebChannelContext + + :param sid: The SID of the WebChannel resource to update. + """ + return WebChannelContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..70ed7b7ac6 --- /dev/null +++ b/twilio/rest/flex_api/v2/flex_user.py @@ -0,0 +1,550 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlexUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlexUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the FlexUserInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + email=email, + user_sid=user_sid, + locale=locale, + ) + + async def update_with_http_info_async( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FlexUserInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> FlexUserInstance: + """ + Fetch the FlexUserInstance + + + :returns: The fetched FlexUserInstance + """ + payload, _, _ = self._fetch() + return FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlexUserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> FlexUserInstance: + """ + Asynchronous coroutine to fetch the FlexUserInstance + + + :returns: The fetched FlexUserInstance + """ + payload, _, _ = await self._fetch_async() + return FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlexUserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(email=email, user_sid=user_sid, locale=locale) + return FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + + def update_with_http_info( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the FlexUserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + email=email, user_sid=user_sid, locale=locale + ) + instance = FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + email=email, user_sid=user_sid, locale=locale + ) + return FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + + async def update_with_http_info_async( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FlexUserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + email=email, user_sid=user_sid, locale=locale + ) + instance = FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..f25f907348 --- /dev/null +++ b/twilio/rest/flex_api/v2/web_channels.py @@ -0,0 +1,271 @@ +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.api_response import ApiResponse + +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, + identity: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "AddressSid": address_sid, + "ChatFriendlyName": chat_friendly_name, + "CustomerFriendlyName": customer_friendly_name, + "PreEngagementData": pre_engagement_data, + "Identity": identity, + } + ) + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + identity: 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. + :param identity: The Identity of the guest user. See the [Conversation User Resource](https://www.twilio.com/docs/conversations/api/user-resource) for an example. + + :returns: The created WebChannelsInstance + """ + payload, _, _ = self._create( + address_sid=address_sid, + ui_version=ui_version, + chat_friendly_name=chat_friendly_name, + customer_friendly_name=customer_friendly_name, + pre_engagement_data=pre_engagement_data, + identity=identity, + ) + return WebChannelsInstance(self._version, payload) + + def create_with_http_info( + 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, + identity: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the WebChannelsInstance and return response metadata + + :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. + :param identity: The Identity of the guest user. See the [Conversation User Resource](https://www.twilio.com/docs/conversations/api/user-resource) for an example. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + address_sid=address_sid, + ui_version=ui_version, + chat_friendly_name=chat_friendly_name, + customer_friendly_name=customer_friendly_name, + pre_engagement_data=pre_engagement_data, + identity=identity, + ) + instance = WebChannelsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + identity: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "AddressSid": address_sid, + "ChatFriendlyName": chat_friendly_name, + "CustomerFriendlyName": customer_friendly_name, + "PreEngagementData": pre_engagement_data, + "Identity": identity, + } + ) + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + identity: 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. + :param identity: The Identity of the guest user. See the [Conversation User Resource](https://www.twilio.com/docs/conversations/api/user-resource) for an example. + + :returns: The created WebChannelsInstance + """ + payload, _, _ = await self._create_async( + address_sid=address_sid, + ui_version=ui_version, + chat_friendly_name=chat_friendly_name, + customer_friendly_name=customer_friendly_name, + pre_engagement_data=pre_engagement_data, + identity=identity, + ) + return WebChannelsInstance(self._version, payload) + + async def create_with_http_info_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, + identity: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WebChannelsInstance and return response metadata + + :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. + :param identity: The Identity of the guest user. See the [Conversation User Resource](https://www.twilio.com/docs/conversations/api/user-resource) for an example. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + address_sid=address_sid, + ui_version=ui_version, + chat_friendly_name=chat_friendly_name, + customer_friendly_name=customer_friendly_name, + pre_engagement_data=pre_engagement_data, + identity=identity, + ) + instance = WebChannelsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..f3cb7f3b25 --- /dev/null +++ b/twilio/rest/frontline_api/v1/user.py @@ -0,0 +1,532 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + return UserInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + instance = UserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + return UserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + instance = UserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, 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 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..fc056efe43 --- /dev/null +++ b/twilio/rest/iam/IamBase.py @@ -0,0 +1,31 @@ +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 twilio.base.domain import Domain +from twilio.rest import Client + + +class IamBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Iam Domain + + :returns: Domain for Iam + """ + super().__init__(twilio, "https://iam.twilio.com") + + 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..cef8af5122 --- /dev/null +++ b/twilio/rest/iam/v1/__init__.py @@ -0,0 +1,90 @@ +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.o_auth_app import OAuthAppList +from twilio.rest.iam.v1.role_permission import RolePermissionList +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._o_auth_apps: Optional[OAuthAppList] = 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 o_auth_apps(self) -> OAuthAppList: + if self._o_auth_apps is None: + self._o_auth_apps = OAuthAppList(self) + return self._o_auth_apps + + def role_permission(self, role_sid: str, role_permission_id: str = None): + """ + Access the RolePermissionList resource + + :param role_sid: The SID of the Role for which Permissions will be fetched. + + :param role_permission_id: Optional instance ID to directly access RolePermissionContext + :returns: RolePermissionList instance if role_permission_id is None, otherwise RolePermissionContext + """ + list_instance = RolePermissionList(self, role_sid) + if role_permission_id is not None: + return list_instance(role_permission_id) + return list_instance + + @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..c99f3ff2a5 --- /dev/null +++ b/twilio/rest/iam/v1/api_key.py @@ -0,0 +1,570 @@ +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.api_response import ApiResponse +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ApiKeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ApiKeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ApiKeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApiKeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the ApiKeyInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + policy=policy, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ApiKeyInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ApiKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ApiKeyInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ApiKeyInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ApiKeyInstance: + """ + Fetch the ApiKeyInstance + + + :returns: The fetched ApiKeyInstance + """ + payload, _, _ = self._fetch() + return ApiKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ApiKeyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ApiKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ApiKeyInstance: + """ + Asynchronous coroutine to fetch the ApiKeyInstance + + + :returns: The fetched ApiKeyInstance + """ + payload, _, _ = await self._fetch_async() + return ApiKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApiKeyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ApiKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(friendly_name=friendly_name, policy=policy) + return ApiKeyInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the ApiKeyInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, policy=policy + ) + instance = ApiKeyInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, policy=policy + ) + return ApiKeyInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ApiKeyInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, policy=policy + ) + instance = ApiKeyInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, 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 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..14bd127d89 --- /dev/null +++ b/twilio/rest/iam/v1/get_api_keys.py @@ -0,0 +1,498 @@ +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.api_response import ApiResponse + +from twilio.base.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. + :ivar flags: + """ + + 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.flags: Optional[List[str]] = payload.get("flags") + + 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 stream_with_http_info( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams GetApiKeysInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + account_sid=account_sid, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams GetApiKeysInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + account_sid=account_sid, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists GetApiKeysInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + account_sid=account_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists GetApiKeysInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + account_sid=account_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with GetApiKeysPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = GetApiKeysPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with GetApiKeysPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = GetApiKeysPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..a89d5cc60b --- /dev/null +++ b/twilio/rest/iam/v1/new_api_key.py @@ -0,0 +1,248 @@ +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.api_response import ApiResponse + +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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + account_sid=account_sid, + friendly_name=friendly_name, + key_type=key_type, + policy=policy, + ) + return NewApiKeyInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the NewApiKeyInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + account_sid=account_sid, + friendly_name=friendly_name, + key_type=key_type, + policy=policy, + ) + instance = NewApiKeyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + account_sid=account_sid, + friendly_name=friendly_name, + key_type=key_type, + policy=policy, + ) + return NewApiKeyInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the NewApiKeyInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + account_sid=account_sid, + friendly_name=friendly_name, + key_type=key_type, + policy=policy, + ) + instance = NewApiKeyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/iam/v1/o_auth_app.py b/twilio/rest/iam/v1/o_auth_app.py new file mode 100644 index 0000000000..1a8e3ecd22 --- /dev/null +++ b/twilio/rest/iam/v1/o_auth_app.py @@ -0,0 +1,835 @@ +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 +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.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 OAuthAppInstance(InstanceResource): + + class IamV1AccountVendorOauthAppCreateRequest(object): + """ + :ivar type: + :ivar friendly_name: + :ivar owner_sid: + :ivar description: + :ivar client_sid: + :ivar policy: + :ivar access_token_ttl: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional[str] = payload.get("type") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.owner_sid: Optional[str] = payload.get("owner_sid") + self.description: Optional[str] = payload.get("description") + self.client_sid: Optional[str] = payload.get("client_sid") + self.policy: Optional[ + OAuthAppList.IamV1OrganizationVendoroauthappPolicy + ] = payload.get("policy") + self.access_token_ttl: Optional[int] = payload.get("access_token_ttl") + + def to_dict(self): + return { + "type": self.type, + "friendly_name": self.friendly_name, + "owner_sid": self.owner_sid, + "description": self.description, + "client_sid": self.client_sid, + "policy": self.policy.to_dict() if self.policy is not None else None, + "access_token_ttl": self.access_token_ttl, + } + + class IamV1AccountVendorOauthAppUpdateRequest(object): + """ + :ivar type: + :ivar friendly_name: + :ivar description: + :ivar policy: + :ivar access_token_ttl: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional[str] = payload.get("type") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.policy: Optional[ + OAuthAppList.IamV1OrganizationVendorOauthAppUpdateRequestPolicy + ] = payload.get("policy") + self.access_token_ttl: Optional[int] = payload.get("access_token_ttl") + + def to_dict(self): + return { + "type": self.type, + "friendly_name": self.friendly_name, + "description": self.description, + "policy": self.policy.to_dict() if self.policy is not None else None, + "access_token_ttl": self.access_token_ttl, + } + + class IamV1OrganizationVendorOauthAppUpdateRequestPolicy(object): + """ + :ivar allow: Set of permissions explicitly allowed + :ivar deny: Set of permissions explicitly denied + """ + + def __init__(self, payload: Dict[str, Any]): + + self.allow: Optional[List[str]] = payload.get("allow") + self.deny: Optional[List[str]] = payload.get("deny") + + def to_dict(self): + return { + "allow": self.allow, + "deny": self.deny, + } + + class IamV1OrganizationVendoroauthappPolicy(object): + """ + :ivar allow: Set of permissions explicitly allowed + :ivar deny: Set of permissions explicitly denied + """ + + def __init__(self, payload: Dict[str, Any]): + + self.allow: Optional[List[str]] = payload.get("allow") + self.deny: Optional[List[str]] = payload.get("deny") + + def to_dict(self): + return { + "allow": self.allow, + "deny": self.deny, + } + + """ + :ivar type: + :ivar sid: + :ivar friendly_name: + :ivar description: + :ivar date_created: + :ivar created_by: + :ivar secret: + :ivar status: + :ivar policy: + :ivar access_token_ttl: + :ivar code: Twilio-specific error code + :ivar message: Error message + :ivar more_info: Link to Error Code References + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.type: Optional[str] = payload.get("type") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.secret: Optional[str] = payload.get("secret") + self.status: Optional[str] = payload.get("status") + self.policy: Optional[str] = payload.get("policy") + self.access_token_ttl: Optional[int] = deserialize.integer( + payload.get("access_token_ttl") + ) + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.more_info: Optional[str] = payload.get("more_info") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[OAuthAppContext] = None + + @property + def _proxy(self) -> "OAuthAppContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OAuthAppContext for this OAuthAppInstance + """ + if self._context is None: + self._context = OAuthAppContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the OAuthAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OAuthAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OAuthAppInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OAuthAppInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def update( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> "OAuthAppInstance": + """ + Update the OAuthAppInstance + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: The updated OAuthAppInstance + """ + return self._proxy.update( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_request, + ) + + async def update_async( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> "OAuthAppInstance": + """ + Asynchronous coroutine to update the OAuthAppInstance + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: The updated OAuthAppInstance + """ + return await self._proxy.update_async( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_request, + ) + + def update_with_http_info( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> ApiResponse: + """ + Update the OAuthAppInstance with HTTP info + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_request, + ) + + async def update_with_http_info_async( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the OAuthAppInstance with HTTP info + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_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 OAuthAppContext(InstanceContext): + + class IamV1AccountVendorOauthAppCreateRequest(object): + """ + :ivar type: + :ivar friendly_name: + :ivar owner_sid: + :ivar description: + :ivar client_sid: + :ivar policy: + :ivar access_token_ttl: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional[str] = payload.get("type") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.owner_sid: Optional[str] = payload.get("owner_sid") + self.description: Optional[str] = payload.get("description") + self.client_sid: Optional[str] = payload.get("client_sid") + self.policy: Optional[ + OAuthAppList.IamV1OrganizationVendoroauthappPolicy + ] = payload.get("policy") + self.access_token_ttl: Optional[int] = payload.get("access_token_ttl") + + def to_dict(self): + return { + "type": self.type, + "friendly_name": self.friendly_name, + "owner_sid": self.owner_sid, + "description": self.description, + "client_sid": self.client_sid, + "policy": self.policy.to_dict() if self.policy is not None else None, + "access_token_ttl": self.access_token_ttl, + } + + class IamV1AccountVendorOauthAppUpdateRequest(object): + """ + :ivar type: + :ivar friendly_name: + :ivar description: + :ivar policy: + :ivar access_token_ttl: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional[str] = payload.get("type") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.policy: Optional[ + OAuthAppList.IamV1OrganizationVendorOauthAppUpdateRequestPolicy + ] = payload.get("policy") + self.access_token_ttl: Optional[int] = payload.get("access_token_ttl") + + def to_dict(self): + return { + "type": self.type, + "friendly_name": self.friendly_name, + "description": self.description, + "policy": self.policy.to_dict() if self.policy is not None else None, + "access_token_ttl": self.access_token_ttl, + } + + class IamV1OrganizationVendorOauthAppUpdateRequestPolicy(object): + """ + :ivar allow: Set of permissions explicitly allowed + :ivar deny: Set of permissions explicitly denied + """ + + def __init__(self, payload: Dict[str, Any]): + + self.allow: Optional[List[str]] = payload.get("allow") + self.deny: Optional[List[str]] = payload.get("deny") + + def to_dict(self): + return { + "allow": self.allow, + "deny": self.deny, + } + + class IamV1OrganizationVendoroauthappPolicy(object): + """ + :ivar allow: Set of permissions explicitly allowed + :ivar deny: Set of permissions explicitly denied + """ + + def __init__(self, payload: Dict[str, Any]): + + self.allow: Optional[List[str]] = payload.get("allow") + self.deny: Optional[List[str]] = payload.get("deny") + + def to_dict(self): + return { + "allow": self.allow, + "deny": self.deny, + } + + def __init__(self, version: Version, sid: str): + """ + Initialize the OAuthAppContext + + :param version: Version that contains the resource + :param sid: Unique ID (sid) of the OAuth app + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Account/OAuthApps/{sid}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the OAuthAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OAuthAppInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OAuthAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OAuthAppInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _update( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = iam_v1_account_vendor_oauth_app_update_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> OAuthAppInstance: + """ + Update the OAuthAppInstance + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: The updated OAuthAppInstance + """ + payload, _, _ = self._update( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_request + ) + return OAuthAppInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> ApiResponse: + """ + Update the OAuthAppInstance and return response metadata + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_request + ) + instance = OAuthAppInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = iam_v1_account_vendor_oauth_app_update_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> OAuthAppInstance: + """ + Asynchronous coroutine to update the OAuthAppInstance + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: The updated OAuthAppInstance + """ + payload, _, _ = await self._update_async( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_request + ) + return OAuthAppInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the OAuthAppInstance and return response metadata + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_request + ) + instance = OAuthAppInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, 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 OAuthAppList(ListResource): + + class IamV1AccountVendorOauthAppCreateRequest(object): + """ + :ivar type: + :ivar friendly_name: + :ivar owner_sid: + :ivar description: + :ivar client_sid: + :ivar policy: + :ivar access_token_ttl: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional[str] = payload.get("type") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.owner_sid: Optional[str] = payload.get("owner_sid") + self.description: Optional[str] = payload.get("description") + self.client_sid: Optional[str] = payload.get("client_sid") + self.policy: Optional[ + OAuthAppList.IamV1OrganizationVendoroauthappPolicy + ] = payload.get("policy") + self.access_token_ttl: Optional[int] = payload.get("access_token_ttl") + + def to_dict(self): + return { + "type": self.type, + "friendly_name": self.friendly_name, + "owner_sid": self.owner_sid, + "description": self.description, + "client_sid": self.client_sid, + "policy": self.policy.to_dict() if self.policy is not None else None, + "access_token_ttl": self.access_token_ttl, + } + + class IamV1AccountVendorOauthAppUpdateRequest(object): + """ + :ivar type: + :ivar friendly_name: + :ivar description: + :ivar policy: + :ivar access_token_ttl: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional[str] = payload.get("type") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.policy: Optional[ + OAuthAppList.IamV1OrganizationVendorOauthAppUpdateRequestPolicy + ] = payload.get("policy") + self.access_token_ttl: Optional[int] = payload.get("access_token_ttl") + + def to_dict(self): + return { + "type": self.type, + "friendly_name": self.friendly_name, + "description": self.description, + "policy": self.policy.to_dict() if self.policy is not None else None, + "access_token_ttl": self.access_token_ttl, + } + + class IamV1OrganizationVendorOauthAppUpdateRequestPolicy(object): + """ + :ivar allow: Set of permissions explicitly allowed + :ivar deny: Set of permissions explicitly denied + """ + + def __init__(self, payload: Dict[str, Any]): + + self.allow: Optional[List[str]] = payload.get("allow") + self.deny: Optional[List[str]] = payload.get("deny") + + def to_dict(self): + return { + "allow": self.allow, + "deny": self.deny, + } + + class IamV1OrganizationVendoroauthappPolicy(object): + """ + :ivar allow: Set of permissions explicitly allowed + :ivar deny: Set of permissions explicitly denied + """ + + def __init__(self, payload: Dict[str, Any]): + + self.allow: Optional[List[str]] = payload.get("allow") + self.deny: Optional[List[str]] = payload.get("deny") + + def to_dict(self): + return { + "allow": self.allow, + "deny": self.deny, + } + + def __init__(self, version: Version): + """ + Initialize the OAuthAppList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Account/OAuthApps" + + def _create( + self, + iam_v1_account_vendor_oauth_app_create_request: IamV1AccountVendorOauthAppCreateRequest, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = iam_v1_account_vendor_oauth_app_create_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + iam_v1_account_vendor_oauth_app_create_request: IamV1AccountVendorOauthAppCreateRequest, + ) -> OAuthAppInstance: + """ + Create the OAuthAppInstance + + :param iam_v1_account_vendor_oauth_app_create_request: + + :returns: The created OAuthAppInstance + """ + payload, _, _ = self._create( + iam_v1_account_vendor_oauth_app_create_request=iam_v1_account_vendor_oauth_app_create_request + ) + return OAuthAppInstance(self._version, payload) + + def create_with_http_info( + self, + iam_v1_account_vendor_oauth_app_create_request: IamV1AccountVendorOauthAppCreateRequest, + ) -> ApiResponse: + """ + Create the OAuthAppInstance and return response metadata + + :param iam_v1_account_vendor_oauth_app_create_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + iam_v1_account_vendor_oauth_app_create_request=iam_v1_account_vendor_oauth_app_create_request + ) + instance = OAuthAppInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + iam_v1_account_vendor_oauth_app_create_request: IamV1AccountVendorOauthAppCreateRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = iam_v1_account_vendor_oauth_app_create_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + iam_v1_account_vendor_oauth_app_create_request: IamV1AccountVendorOauthAppCreateRequest, + ) -> OAuthAppInstance: + """ + Asynchronously create the OAuthAppInstance + + :param iam_v1_account_vendor_oauth_app_create_request: + + :returns: The created OAuthAppInstance + """ + payload, _, _ = await self._create_async( + iam_v1_account_vendor_oauth_app_create_request=iam_v1_account_vendor_oauth_app_create_request + ) + return OAuthAppInstance(self._version, payload) + + async def create_with_http_info_async( + self, + iam_v1_account_vendor_oauth_app_create_request: IamV1AccountVendorOauthAppCreateRequest, + ) -> ApiResponse: + """ + Asynchronously create the OAuthAppInstance and return response metadata + + :param iam_v1_account_vendor_oauth_app_create_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + iam_v1_account_vendor_oauth_app_create_request=iam_v1_account_vendor_oauth_app_create_request + ) + instance = OAuthAppInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def get(self, sid: str) -> OAuthAppContext: + """ + Constructs a OAuthAppContext + + :param sid: Unique ID (sid) of the OAuth app + """ + return OAuthAppContext(self._version, sid=sid) + + def __call__(self, sid: str) -> OAuthAppContext: + """ + Constructs a OAuthAppContext + + :param sid: Unique ID (sid) of the OAuth app + """ + return OAuthAppContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/iam/v1/role_permission.py b/twilio/rest/iam/v1/role_permission.py new file mode 100644 index 0000000000..833dafdf60 --- /dev/null +++ b/twilio/rest/iam/v1/role_permission.py @@ -0,0 +1,472 @@ +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, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RolePermissionInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the Permission resource. + :ivar namespace: The namespace of the permission (e.g., twilio). + :ivar product: The product the permission belongs to (e.g., iam). + :ivar resource: The resource the permission applies to (e.g., roles). + :ivar action: The action granted by the permission (e.g., read). + :ivar external_description: The external description of the permission. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], role_sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.namespace: Optional[str] = payload.get("namespace") + self.product: Optional[str] = payload.get("product") + self.resource: Optional[str] = payload.get("resource") + self.action: Optional[str] = payload.get("action") + self.external_description: Optional[str] = payload.get("externalDescription") + + self._solution = { + "role_sid": role_sid or self.role_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RolePermissionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RolePermissionInstance: + """ + Build an instance of RolePermissionInstance + + :param payload: Payload response from the API + """ + + return RolePermissionInstance( + self._version, payload, role_sid=self._solution["role_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RolePermissionList(ListResource): + + def __init__(self, version: Version, role_sid: str): + """ + Initialize the RolePermissionList + + :param version: Version that contains the resource + :param role_sid: The SID of the Role for which Permissions will be fetched. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "role_sid": role_sid, + } + self._uri = "/Roles/{role_sid}/Permissions".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RolePermissionInstance]: + """ + Streams RolePermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RolePermissionInstance]: + """ + Asynchronously streams RolePermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RolePermissionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RolePermissionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RolePermissionInstance]: + """ + Lists RolePermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RolePermissionInstance]: + """ + Asynchronously lists RolePermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RolePermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RolePermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePermissionPage: + """ + Retrieve a single page of RolePermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RolePermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePermissionPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePermissionPage: + """ + Asynchronously retrieve a single page of RolePermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RolePermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePermissionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePermissionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RolePermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePermissionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RolePermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> RolePermissionPage: + """ + Retrieve a specific page of RolePermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RolePermissionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RolePermissionPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> RolePermissionPage: + """ + Asynchronously retrieve a specific page of RolePermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RolePermissionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePermissionPage(self._version, response, solution=self._solution) + + 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..72d5da3fe9 --- /dev/null +++ b/twilio/rest/iam/v1/token.py @@ -0,0 +1,301 @@ +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.api_response import ApiResponse + +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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + 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, + ) + return TokenInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the TokenInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + 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, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + 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, + ) + return TokenInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the TokenInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + 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, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..e2d5c3328d --- /dev/null +++ b/twilio/rest/insights/InsightsBase.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.insights.v1 import V1 +from twilio.rest.insights.v2 import V2 +from twilio.rest.insights.v3 import V3 + + +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 + self._v2: Optional[V2] = None + self._v3: Optional[V3] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Insights + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Insights + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Insights + """ + 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/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..89516703cd 100644 --- a/twilio/rest/insights/v1/call/__init__.py +++ b/twilio/rest/insights/v1/call/__init__.py @@ -1,304 +1,343 @@ -# 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.api_response import ApiResponse 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. """ - - def __init__(self, version): - """ - Initialize the CallList +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, + } - :param Version version: Version that contains the resource + self._context: Optional[CallContext] = None - :returns: twilio.rest.insights.v1.call.CallList - :rtype: twilio.rest.insights.v1.call.CallList + @property + def _proxy(self) -> "CallContext": """ - super(CallList, 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: CallContext for this CallInstance + """ + 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Fetch the CallInstance with HTTP info - :returns: Machine friendly representation - :rtype: str - """ - return '' + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() -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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Initialize the CallPage + Asynchronous coroutine to fetch the CallInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - super(CallPage, self).__init__(version, response) + return await self._proxy.fetch_with_http_info_async() - # Path Solution - self._solution = solution + @property + def annotation(self) -> AnnotationList: + """ + Access the annotation + """ + return self._proxy.annotation - def get_instance(self, payload): + @property + def summary(self) -> CallSummaryList: """ - Build an instance of CallInstance + Access the summary + """ + return self._proxy.summary - :param dict payload: Payload response from the API + @property + def events(self) -> EventList: + """ + 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) -> tuple: """ - Fetch the CallInstance + Internal helper for fetch operation - :returns: The fetched CallInstance - :rtype: twilio.rest.insights.v1.call.CallInstance + Returns: + tuple: (payload, status_code, headers) """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return CallInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) - @property - def events(self): - """ - Access the events + headers["Accept"] = "application/json" - :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 + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - @property - def metrics(self): + def fetch(self) -> CallInstance: """ - Access the metrics + Fetch the CallInstance + - :returns: twilio.rest.insights.v1.call.metric.MetricList - :rtype: twilio.rest.insights.v1.call.metric.MetricList + :returns: The fetched CallInstance """ - if self._metrics is None: - self._metrics = MetricList(self._version, call_sid=self._solution['sid'], ) - return self._metrics + payload, _, _ = self._fetch() + return CallInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - @property - def summary(self): + def fetch_with_http_info(self) -> ApiResponse: """ - Access the summary + Fetch the CallInstance and return response metadata - :returns: twilio.rest.insights.v1.call.summary.CallSummaryList - :rtype: twilio.rest.insights.v1.call.summary.CallSummaryList + + :returns: ApiResponse with instance, status code, and headers """ - if self._summary is None: - self._summary = CallSummaryList(self._version, call_sid=self._solution['sid'], ) - return self._summary + payload, status_code, headers = self._fetch() + instance = CallInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, payload, sid=None): + async def fetch_async(self) -> CallInstance: """ - Initialize the CallInstance + Asynchronous coroutine to fetch the CallInstance - :returns: twilio.rest.insights.v1.call.CallInstance - :rtype: twilio.rest.insights.v1.call.CallInstance + + :returns: The fetched CallInstance """ - super(CallInstance, self).__init__(version) + payload, _, _ = await self._fetch_async() + return CallInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'url': payload.get('url'), - 'links': payload.get('links'), - } + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CallInstance and return response metadata - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): + :returns: ApiResponse with instance, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, status_code, headers = await self._fetch_async() + instance = CallInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: CallContext for this CallInstance - :rtype: twilio.rest.insights.v1.call.CallContext + @property + def annotation(self) -> AnnotationList: """ - if self._context is None: - self._context = CallContext(self._version, sid=self._solution['sid'], ) - return self._context + Access the annotation + """ + 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..5bda909b68 --- /dev/null +++ b/twilio/rest/insights/v1/call/annotation.py @@ -0,0 +1,665 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AnnotationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AnnotationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the AnnotationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AnnotationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AnnotationInstance: + """ + Fetch the AnnotationInstance + + + :returns: The fetched AnnotationInstance + """ + payload, _, _ = self._fetch() + return AnnotationInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AnnotationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AnnotationInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AnnotationInstance: + """ + Asynchronous coroutine to fetch the AnnotationInstance + + + :returns: The fetched AnnotationInstance + """ + payload, _, _ = await self._fetch_async() + return AnnotationInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AnnotationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AnnotationInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) + return AnnotationInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the AnnotationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) + instance = AnnotationInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) + return AnnotationInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AnnotationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) + instance = AnnotationInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..edb1ba1178 --- /dev/null +++ b/twilio/rest/insights/v1/call/call_summary.py @@ -0,0 +1,427 @@ +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.api_response import ApiResponse +from twilio.base.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: `object` The calling party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + :ivar to: `object` The called party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + :ivar carrier_edge: `object` Contains metrics and properties for the Twilio media gateway of a PSTN call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar client_edge: `object` Contains metrics and properties for the Twilio media gateway of a Client call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sdk_edge: `object` Contains metrics and properties for the SDK sensor library for Client calls. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sip_edge: `object` Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :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: `object` Attributes capturing call-flow-specific details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#attributes-object) for the object properties. + :ivar properties: `object` Contains edge-agnostic call-level details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#properties-object) for the object properties. + :ivar trust: `object` Contains trusted communications details including Branded Call and verified caller ID. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#trust-object) for the object properties. + :ivar annotation: `object` 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. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#annotation-object) for the object properties. + """ + + 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 fetch_with_http_info( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> ApiResponse: + """ + Fetch the CallSummaryInstance with HTTP info + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + processing_state=processing_state, + ) + + async def fetch_with_http_info_async( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CallSummaryInstance with HTTP info + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "ProcessingState": processing_state, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = self._fetch(processing_state=processing_state) + return CallSummaryInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + + def fetch_with_http_info( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> ApiResponse: + """ + Fetch the CallSummaryInstance and return response metadata + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(processing_state=processing_state) + instance = CallSummaryInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "ProcessingState": processing_state, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(processing_state=processing_state) + return CallSummaryInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + + async def fetch_with_http_info_async( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CallSummaryInstance and return response metadata + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + processing_state=processing_state + ) + instance = CallSummaryInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 f026acc0e2..ca9b99ccc6 100644 --- a/twilio/rest/insights/v1/call/event.py +++ b/twilio/rest/insights/v1/call/event.py @@ -1,315 +1,529 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class EventInstance(InstanceResource): + + class Level(object): + UNKNOWN = "UNKNOWN" + DEBUG = "DEBUG" + INFO = "INFO" + WARNING = "WARNING" + ERROR = "ERROR" + + class TwilioEdge(object): + UNKNOWN_EDGE = "unknown_edge" + CARRIER_EDGE = "carrier_edge" + SIP_EDGE = "sip_edge" + SDK_EDGE = "sdk_edge" + CLIENT_EDGE = "client_edge" + + """ + :ivar timestamp: Event time. + :ivar call_sid: The unique SID identifier of the Call. + :ivar account_sid: The unique SID identifier of the Account. + :ivar edge: + :ivar group: Event group. + :ivar level: + :ivar name: Event name. + :ivar carrier_edge: `object` 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. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sip_edge: `object` 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. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sdk_edge: `object` 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. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar client_edge: `object` Represents the Twilio media gateway for Client calls. The events here describe the call lifecycle as reported by Twilio's Voice SDK media gateways. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): + super().__init__(version) + + self.timestamp: Optional[str] = payload.get("timestamp") + self.call_sid: Optional[str] = payload.get("call_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.edge: Optional["EventInstance.TwilioEdge"] = payload.get("edge") + self.group: Optional[str] = payload.get("group") + self.level: Optional["EventInstance.Level"] = payload.get("level") + self.name: Optional[str] = payload.get("name") + self.carrier_edge: Optional[Dict[str, object]] = payload.get("carrier_edge") + self.sip_edge: Optional[Dict[str, object]] = payload.get("sip_edge") + self.sdk_edge: Optional[Dict[str, object]] = payload.get("sdk_edge") + self.client_edge: Optional[Dict[str, object]] = payload.get("client_edge") + + self._solution = { + "call_sid": call_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EventPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: + """ + Build an instance of EventInstance + + :param payload: Payload response from the API + """ + + return EventInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class EventList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - 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): + def __init__(self, version: Version, call_sid: str): """ Initialize the EventList - :param Version version: Version that contains the resource - :param call_sid: The call_sid + :param version: Version that contains the resource + :param call_sid: The unique SID identifier of the Call. - :returns: twilio.rest.insights.v1.call.event.EventList - :rtype: twilio.rest.insights.v1.call.event.EventList """ - super(EventList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'call_sid': call_sid, } - self._uri = '/Voice/{call_sid}/Events'.format(**self._solution) + self._solution = { + "call_sid": call_sid, + } + self._uri = "/Voice/{call_sid}/Events".format(**self._solution) - def stream(self, edge=values.unset, limit=None, page_size=None): + def stream( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EventInstance]: """ Streams EventInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param EventInstance.TwilioEdge edge: The edge - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 "EventInstance.TwilioEdge" edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.insights.v1.call.event.EventInstance] """ limits = self._version.read_limits(limit, page_size) + page = self.page(edge=edge, page_size=limits["page_size"]) - page = self.page(edge=edge, page_size=limits['page_size'], ) + return self._version.stream(page, limits["limit"]) - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, edge=values.unset, limit=None, page_size=None): + async def stream_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[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. + Asynchronously streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :param EventInstance.TwilioEdge edge: The edge - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 "EventInstance.TwilioEdge" edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.insights.v1.call.event.EventInstance] - """ - return list(self.stream(edge=edge, limit=limit, page_size=page_size, )) - - def page(self, edge=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): """ - Retrieve a single page of EventInstance records from the API. - Request is executed immediately + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(edge=edge, page_size=limits["page_size"]) - :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 + return self._version.stream_async(page, limits["limit"]) - :returns: Page of EventInstance - :rtype: twilio.rest.insights.v1.call.event.EventPage + def stream_with_http_info( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - data = values.of({ - 'Edge': edge, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Streams EventInstance and returns headers from first page - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return EventPage(self._version, response, self._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_page(self, target_url): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Retrieve a specific page of EventInstance records from the API. - Request is executed immediately + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + edge=edge, page_size=limits["page_size"] + ) - :param str target_url: API-generated URL for the requested results page + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: Page of EventInstance - :rtype: twilio.rest.insights.v1.call.event.EventPage + async def stream_with_http_info_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronously streams EventInstance and returns headers from first page - return EventPage(self._version, response, self._solution) - def __repr__(self): - """ - Provide a friendly representation + :param "EventInstance.TwilioEdge" edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Machine friendly representation - :rtype: str + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return '' - + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + edge=edge, page_size=limits["page_size"] + ) -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. """ + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - def __init__(self, version, response, solution): + def list( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: """ - Initialize the EventPage + 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 Version version: Version that contains the resource - :param Response response: Response from the API - :param call_sid: The call_sid + :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: twilio.rest.insights.v1.call.event.EventPage - :rtype: twilio.rest.insights.v1.call.event.EventPage + :returns: list that will contain up to limit results """ - super(EventPage, self).__init__(version, response) - # Path Solution - self._solution = solution + return list( + self.stream( + edge=edge, + limit=limit, + page_size=page_size, + ) + ) - def get_instance(self, payload): + async def list_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: """ - Build an instance of 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 dict payload: Payload response from the API + :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 list_with_http_info( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EventInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + edge=edge, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: twilio.rest.insights.v1.call.event.EventInstance - :rtype: twilio.rest.insights.v1.call.event.EventInstance + async def list_with_http_info_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return EventInstance(self._version, payload, call_sid=self._solution['call_sid'], ) + Asynchronously lists EventInstance and returns headers from first page - def __repr__(self): + + :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: ApiResponse with list of instances, status code, and headers """ - Provide a friendly representation + generator, status_code, headers = await self.stream_with_http_info_async( + edge=edge, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: Machine friendly representation - :rtype: str + 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): + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, solution=self._solution) + + async def page_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: """ - Initialize the EventInstance + Asynchronously retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - :returns: twilio.rest.insights.v1.call.event.EventInstance - :rtype: twilio.rest.insights.v1.call.event.EventInstance + :returns: Page of EventInstance """ - super(EventInstance, self).__init__(version) + data = values.of( + { + "Edge": edge, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - # 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'), - } + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Context - self._context = None - self._solution = {'call_sid': call_sid, } + headers["Accept"] = "application/json" - @property - def timestamp(self): - """ - :returns: The timestamp - :rtype: unicode - """ - return self._properties['timestamp'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, solution=self._solution) - @property - def call_sid(self): - """ - :returns: The call_sid - :rtype: unicode + def page_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['call_sid'] + Retrieve a single page with response metadata - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def edge(self): - """ - :returns: The edge - :rtype: EventInstance.TwilioEdge - """ - return self._properties['edge'] + :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 group(self): - """ - :returns: The group - :rtype: unicode + :returns: ApiResponse with EventPage, status code, and headers """ - return self._properties['group'] + data = values.of( + { + "Edge": edge, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def level(self): - """ - :returns: The level - :rtype: EventInstance.Level - """ - return self._properties['level'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def name(self): - """ - :returns: The name - :rtype: unicode - """ - return self._properties['name'] + headers["Accept"] = "application/json" - @property - def carrier_edge(self): - """ - :returns: The carrier_edge - :rtype: dict - """ - return self._properties['carrier_edge'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventPage, status code, and headers + """ + data = values.of( + { + "Edge": edge, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def sip_edge(self): - """ - :returns: The sip_edge - :rtype: dict - """ - return self._properties['sip_edge'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def sdk_edge(self): + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> EventPage: """ - :returns: The sdk_edge - :rtype: dict + 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['sdk_edge'] + response = self._version.domain.twilio.request("GET", target_url) + return EventPage(self._version, response, solution=self._solution) - @property - def client_edge(self): + async def get_page_async(self, target_url: str) -> EventPage: """ - :returns: The client_edge - :rtype: dict + 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['client_edge'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return EventPage(self._version, response, solution=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 8b3e051198..7cf72240b7 100644 --- a/twilio/rest/insights/v1/call/metric.py +++ b/twilio/rest/insights/v1/call/metric.py @@ -1,303 +1,560 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class MetricInstance(InstanceResource): + + class StreamDirection(object): + UNKNOWN = "unknown" + INBOUND = "inbound" + OUTBOUND = "outbound" + BOTH = "both" + + class TwilioEdge(object): + UNKNOWN_EDGE = "unknown_edge" + CARRIER_EDGE = "carrier_edge" + SIP_EDGE = "sip_edge" + SDK_EDGE = "sdk_edge" + CLIENT_EDGE = "client_edge" + + """ + :ivar timestamp: Timestamp of metric sample. Samples are taken every 10 seconds and contain the metrics for the previous 10 seconds. + :ivar call_sid: The unique SID identifier of the Call. + :ivar account_sid: The unique SID identifier of the Account. + :ivar edge: + :ivar direction: + :ivar carrier_edge: Contains metrics and properties for the Twilio media gateway of a PSTN call. + :ivar sip_edge: Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. + :ivar sdk_edge: Contains metrics and properties for the SDK sensor library for Client calls. + :ivar client_edge: Contains metrics and properties for the Twilio media gateway of a Client call. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): + super().__init__(version) + + self.timestamp: Optional[str] = payload.get("timestamp") + self.call_sid: Optional[str] = payload.get("call_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.edge: Optional["MetricInstance.TwilioEdge"] = payload.get("edge") + self.direction: Optional["MetricInstance.StreamDirection"] = payload.get( + "direction" + ) + self.carrier_edge: Optional[Dict[str, object]] = payload.get("carrier_edge") + self.sip_edge: Optional[Dict[str, object]] = payload.get("sip_edge") + self.sdk_edge: Optional[Dict[str, object]] = payload.get("sdk_edge") + self.client_edge: Optional[Dict[str, object]] = payload.get("client_edge") + + self._solution = { + "call_sid": call_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MetricPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MetricInstance: + """ + Build an instance of MetricInstance + + :param payload: Payload response from the API + """ + + return MetricInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class MetricList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - 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): + def __init__(self, version: Version, call_sid: str): """ Initialize the MetricList - :param Version version: Version that contains the resource - :param call_sid: The call_sid + :param version: Version that contains the resource + :param call_sid: The unique SID identifier of the Call. - :returns: twilio.rest.insights.v1.call.metric.MetricList - :rtype: twilio.rest.insights.v1.call.metric.MetricList """ - super(MetricList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'call_sid': call_sid, } - self._uri = '/Voice/{call_sid}/Metrics'.format(**self._solution) + self._solution = { + "call_sid": call_sid, + } + self._uri = "/Voice/{call_sid}/Metrics".format(**self._solution) - def stream(self, edge=values.unset, direction=values.unset, limit=None, - page_size=None): + def stream( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MetricInstance]: """ Streams MetricInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param MetricInstance.TwilioEdge edge: The edge - :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) + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.insights.v1.call.metric.MetricInstance] """ limits = self._version.read_limits(limit, page_size) + page = self.page(edge=edge, direction=direction, page_size=limits["page_size"]) - page = self.page(edge=edge, direction=direction, page_size=limits['page_size'], ) + return self._version.stream(page, limits["limit"]) - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, edge=values.unset, direction=values.unset, limit=None, - page_size=None): + 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]: """ - Lists MetricInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronously streams MetricInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :param MetricInstance.TwilioEdge edge: The edge - :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) + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.insights.v1.call.metric.MetricInstance] - """ - return list(self.stream(edge=edge, direction=direction, limit=limit, page_size=page_size, )) - - def page(self, edge=values.unset, direction=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): """ - Retrieve a single page of MetricInstance records from the API. - Request is executed immediately + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + edge=edge, direction=direction, page_size=limits["page_size"] + ) - :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 + return self._version.stream_async(page, limits["limit"]) - :returns: Page of MetricInstance - :rtype: twilio.rest.insights.v1.call.metric.MetricPage + def stream_with_http_info( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - data = values.of({ - 'Edge': edge, - 'Direction': direction, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Streams MetricInstance and returns headers from first page - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return MetricPage(self._version, response, self._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_page(self, target_url): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Retrieve a specific page of MetricInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of MetricInstance - :rtype: twilio.rest.insights.v1.call.metric.MetricPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + edge=edge, direction=direction, page_size=limits["page_size"] ) - return MetricPage(self._version, response, self._solution) + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - def __repr__(self): + async def stream_with_http_info_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, + ) -> tuple: """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' + Asynchronously streams MetricInstance and returns headers from first page -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: tuple of (generator, status_code, headers) where generator yields instances """ - Initialize the MetricPage + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + 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 + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: twilio.rest.insights.v1.call.metric.MetricPage - :rtype: twilio.rest.insights.v1.call.metric.MetricPage + 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]: """ - super(MetricPage, self).__init__(version, response) + Lists MetricInstance 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 = 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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + 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 get_instance(self, payload): + 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]: """ - Build an instance of MetricInstance - - :param dict payload: Payload response from the API + 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: twilio.rest.insights.v1.call.metric.MetricInstance - :rtype: twilio.rest.insights.v1.call.metric.MetricInstance + :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 list_with_http_info( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MetricInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + edge=edge, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists MetricInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + edge=edge, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 MetricInstance(self._version, payload, call_sid=self._solution['call_sid'], ) + Retrieve a single page of MetricInstance records from the API. + Request is executed immediately - def __repr__(self): - """ - Provide a friendly representation + :param edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - :returns: Machine friendly representation - :rtype: str + :returns: Page of MetricInstance """ - return '' + data = values.of( + { + "Edge": edge, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -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. """ + headers["Accept"] = "application/json" - class TwilioEdge(object): - UNKNOWN_EDGE = "unknown_edge" - CARRIER_EDGE = "carrier_edge" - SIP_EDGE = "sip_edge" - SDK_EDGE = "sdk_edge" - CLIENT_EDGE = "client_edge" + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MetricPage(self._version, response, solution=self._solution) + + async def page_async( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MetricPage: + """ + Asynchronously retrieve a single page of MetricInstance records from the API. + Request is executed immediately - class StreamDirection(object): - UNKNOWN = "unknown" - INBOUND = "inbound" - OUTBOUND = "outbound" - BOTH = "both" + :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 - def __init__(self, version, payload, call_sid): + :returns: Page of MetricInstance """ - Initialize the MetricInstance + data = values.of( + { + "Edge": edge, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: twilio.rest.insights.v1.call.metric.MetricInstance - :rtype: twilio.rest.insights.v1.call.metric.MetricInstance - """ - super(MetricInstance, self).__init__(version) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # 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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'call_sid': call_sid, } + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MetricPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MetricPage, status code, and headers + """ + data = values.of( + { + "Edge": edge, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def timestamp(self): - """ - :returns: The timestamp - :rtype: unicode - """ - return self._properties['timestamp'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def call_sid(self): - """ - :returns: The call_sid - :rtype: unicode - """ - return self._properties['call_sid'] + headers["Accept"] = "application/json" - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MetricPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MetricPage, status code, and headers + """ + data = values.of( + { + "Edge": edge, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def edge(self): - """ - :returns: The edge - :rtype: MetricInstance.TwilioEdge - """ - return self._properties['edge'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def direction(self): - """ - :returns: The direction - :rtype: MetricInstance.StreamDirection - """ - return self._properties['direction'] + headers["Accept"] = "application/json" - @property - def carrier_edge(self): - """ - :returns: The carrier_edge - :rtype: dict - """ - return self._properties['carrier_edge'] + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MetricPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def sip_edge(self): + def get_page(self, target_url: str) -> MetricPage: """ - :returns: The sip_edge - :rtype: dict - """ - return self._properties['sip_edge'] + Retrieve a specific page of MetricInstance records from the API. + Request is executed immediately - @property - def sdk_edge(self): - """ - :returns: The sdk_edge - :rtype: dict + :param target_url: API-generated URL for the requested results page + + :returns: Page of MetricInstance """ - return self._properties['sdk_edge'] + response = self._version.domain.twilio.request("GET", target_url) + return MetricPage(self._version, response, solution=self._solution) - @property - def client_edge(self): + async def get_page_async(self, target_url: str) -> MetricPage: """ - :returns: The client_edge - :rtype: dict + Asynchronously retrieve a specific page of MetricInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MetricInstance """ - return self._properties['client_edge'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return MetricPage(self._version, response, solution=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..c1de69c6d5 --- /dev/null +++ b/twilio/rest/insights/v1/call_summaries.py @@ -0,0 +1,1885 @@ +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.api_response import ApiResponse + +from twilio.base.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: `object` The calling party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + :ivar to: `object` The called party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + :ivar carrier_edge: `object` Contains metrics and properties for the Twilio media gateway of a PSTN call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar client_edge: `object` Contains metrics and properties for the Twilio media gateway of a Client call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sdk_edge: `object` Contains metrics and properties for the SDK sensor library for Client calls. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sip_edge: `object` Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :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: `object` Attributes capturing call-flow-specific details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#attributes-object) for the object properties. + :ivar properties: `object` Contains edge-agnostic call-level details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#properties-object) for the object properties. + :ivar trust: `object` Contains trusted communications details including Branded Call and verified caller ID. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#trust-object) for the object properties. + :ivar annotation: `object` 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. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#annotation-object) for the object properties. + """ + + 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, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: 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 bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band 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, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, + 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, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: 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 bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band 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, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, + 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 stream_with_http_info( + 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, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: 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, + ) -> tuple: + """ + Streams CallSummariesInstance and returns headers from first page + + + :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 bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: 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, + ) -> tuple: + """ + Asynchronously streams CallSummariesInstance and returns headers from first page + + + :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 bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, + 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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: 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 bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band 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, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, + 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, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: 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 bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band 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, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, + 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 list_with_http_info( + 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, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: 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, + ) -> ApiResponse: + """ + Lists CallSummariesInstance and returns headers from first page + + + :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 bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: 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, + ) -> ApiResponse: + """ + Asynchronously lists CallSummariesInstance and returns headers from first page + + + :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 bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, + 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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: 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 branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band 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, + "BrandedLogo": serialize.boolean_to_string(branded_logo), + "BrandedType": branded_type, + "BrandedUseCase": branded_use_case, + "BrandedCallReason": branded_call_reason, + "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, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: 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 branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band 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, + "BrandedLogo": serialize.boolean_to_string(branded_logo), + "BrandedType": branded_type, + "BrandedUseCase": branded_use_case, + "BrandedCallReason": branded_call_reason, + "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 page_with_http_info( + 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, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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 branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band 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: ApiResponse with CallSummariesPage, status code, and headers + """ + 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, + "BrandedLogo": serialize.boolean_to_string(branded_logo), + "BrandedType": branded_type, + "BrandedUseCase": branded_use_case, + "BrandedCallReason": branded_call_reason, + "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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CallSummariesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: 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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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 branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band 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: ApiResponse with CallSummariesPage, status code, and headers + """ + 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, + "BrandedLogo": serialize.boolean_to_string(branded_logo), + "BrandedType": branded_type, + "BrandedUseCase": branded_use_case, + "BrandedCallReason": branded_call_reason, + "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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CallSummariesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..72a54a8e96 --- /dev/null +++ b/twilio/rest/insights/v1/conference/__init__.py @@ -0,0 +1,1155 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConferenceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConferenceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConferenceInstance: + """ + Fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + payload, _, _ = self._fetch() + return ConferenceInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConferenceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConferenceInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConferenceInstance: + """ + Asynchronous coroutine to fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + payload, _, _ = await self._fetch_async() + return ConferenceInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConferenceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConferenceInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams ConferenceInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams ConferenceInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists ConferenceInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists ConferenceInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ConferencePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConferencePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ConferencePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConferencePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..ce953db174 --- /dev/null +++ b/twilio/rest/insights/v1/conference/conference_participant.py @@ -0,0 +1,1004 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the ConferenceParticipantInstance with HTTP info + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + events=events, + metrics=metrics, + ) + + async def fetch_with_http_info_async( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConferenceParticipantInstance with HTTP info + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Events": events, + "Metrics": metrics, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = self._fetch(events=events, metrics=metrics) + return ConferenceParticipantInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def fetch_with_http_info( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the ConferenceParticipantInstance and return response metadata + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(events=events, metrics=metrics) + instance = ConferenceParticipantInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Events": events, + "Metrics": metrics, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(events=events, metrics=metrics) + return ConferenceParticipantInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + participant_sid=self._solution["participant_sid"], + ) + + async def fetch_with_http_info_async( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConferenceParticipantInstance and return response metadata + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + events=events, metrics=metrics + ) + instance = ConferenceParticipantInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams ConferenceParticipantInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + participant_sid=participant_sid, + label=label, + events=events, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams ConferenceParticipantInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + participant_sid=participant_sid, + label=label, + events=events, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists ConferenceParticipantInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + participant_sid=participant_sid, + label=label, + events=events, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists ConferenceParticipantInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + participant_sid=participant_sid, + label=label, + events=events, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution + ) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ConferenceParticipantPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConferenceParticipantPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ConferenceParticipantPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConferenceParticipantPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..c754e43850 --- /dev/null +++ b/twilio/rest/insights/v1/room/__init__.py @@ -0,0 +1,985 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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" + + """ + :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() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoomInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoomInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoomInstance: + """ + Fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + payload, _, _ = self._fetch() + return RoomInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoomInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoomInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RoomInstance: + """ + Asynchronous coroutine to fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + payload, _, _ = await self._fetch_async() + return RoomInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoomInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoomInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams RoomInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + room_type=room_type, + codec=codec, + room_name=room_name, + created_after=created_after, + created_before=created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams RoomInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + room_type=room_type, + codec=codec, + room_name=room_name, + created_after=created_after, + created_before=created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists RoomInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + room_type=room_type, + codec=codec, + room_name=room_name, + created_after=created_after, + created_before=created_before, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists RoomInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with RoomPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RoomPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with RoomPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RoomPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..9ae8554b95 --- /dev/null +++ b/twilio/rest/insights/v1/room/participant.py @@ -0,0 +1,747 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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" + + """ + :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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = self._fetch() + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = await self._fetch_async() + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..daf49229a9 --- /dev/null +++ b/twilio/rest/insights/v1/setting.py @@ -0,0 +1,523 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info( + self, subaccount_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the SettingInstance with HTTP info + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + subaccount_sid=subaccount_sid, + ) + + async def fetch_with_http_info_async( + self, subaccount_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SettingInstance with HTTP info + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SettingInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + + async def update_with_http_info_async( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SettingInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "SubaccountSid": subaccount_sid, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = self._fetch(subaccount_sid=subaccount_sid) + return SettingInstance( + self._version, + payload, + ) + + def fetch_with_http_info( + self, subaccount_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the SettingInstance and return response metadata + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(subaccount_sid=subaccount_sid) + instance = SettingInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, subaccount_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "SubaccountSid": subaccount_sid, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(subaccount_sid=subaccount_sid) + return SettingInstance( + self._version, + payload, + ) + + async def fetch_with_http_info_async( + self, subaccount_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SettingInstance and return response metadata + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + subaccount_sid=subaccount_sid + ) + instance = SettingInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + return SettingInstance(self._version, payload) + + def update_with_http_info( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SettingInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + instance = SettingInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + return SettingInstance(self._version, payload) + + async def update_with_http_info_async( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SettingInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + instance = SettingInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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/insights/v2/__init__.py b/twilio/rest/insights/v2/__init__.py new file mode 100644 index 0000000000..9f2e26d1f0 --- /dev/null +++ b/twilio/rest/insights/v2/__init__.py @@ -0,0 +1,73 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Sample/reference Twilio API. + This is the reference API for the rest-proxy server. + + NOTE: This 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.v2.inbound import InboundList +from twilio.rest.insights.v2.outbound import OutboundList +from twilio.rest.insights.v2.report import ReportList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Insights + + :param domain: The Twilio.insights domain + """ + super().__init__(domain, "v2") + self._reports: Optional[ReportList] = None + + def inbound(self, report_id: str, inbound_id: str = None): + """ + Access the InboundList resource + + :param report_id: A unique Report Id. + + :param inbound_id: Optional instance ID to directly access InboundContext + :returns: InboundList instance if inbound_id is None, otherwise InboundContext + """ + list_instance = InboundList(self, report_id) + if inbound_id is not None: + return list_instance(inbound_id) + return list_instance + + def outbound(self, report_id: str, outbound_id: str = None): + """ + Access the OutboundList resource + + :param report_id: A unique Report Id. + + :param outbound_id: Optional instance ID to directly access OutboundContext + :returns: OutboundList instance if outbound_id is None, otherwise OutboundContext + """ + list_instance = OutboundList(self, report_id) + if outbound_id is not None: + return list_instance(outbound_id) + return list_instance + + @property + def reports(self) -> ReportList: + if self._reports is None: + self._reports = ReportList(self) + return self._reports + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/insights/v2/inbound.py b/twilio/rest/insights/v2/inbound.py new file mode 100644 index 0000000000..47bf2a0266 --- /dev/null +++ b/twilio/rest/insights/v2/inbound.py @@ -0,0 +1,1124 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Sample/reference Twilio API. + This is the reference API for the rest-proxy server. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do 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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InboundInstance(InstanceResource): + + class InsightsV2CreatePhoneNumbersReportRequest(object): + """ + :ivar time_range: + :ivar filters: + :ivar size: The number of max available top Phone Numbers to generate. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + InboundList.InsightsV2CreatePhoneNumbersReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[InboundList.PhoneNumberReportFilter]] = ( + payload.get("filters") + ) + self.size: Optional[int] = payload.get("size") + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + "size": self.size, + } + + class InsightsV2CreatePhoneNumbersReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class PhoneNumberReportFilter(object): + """ + :ivar key: The name of the filter + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportStatus(object): + CREATED = "created" + RUNNING = "running" + COMPLETED = "completed" + + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar report_id: The report identifier as Voice Insights Report TTID. + :ivar status: + :ivar request_meta: + :ivar url: The URL of this resource. + :ivar handle: Inbound phone number handle represented in the report. + :ivar total_calls: Total number of calls made with the given handle during the report period. + :ivar call_answer_score: The call answer score measures customers behavior to the delivered calls. The score is a value between 0 and 100, where 100 indicates that all calls were successfully answered. + :ivar call_state_percentage: + :ivar silent_calls_percentage: Percentage of inbound calls with silence tags over total outbound calls. A silent tag is indicative of a connectivity issue or muted audio. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], report_id: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.report_id: Optional[str] = payload.get("report_id") + self.status: Optional["InboundInstance.str"] = payload.get("status") + self.request_meta: Optional[str] = payload.get("request_meta") + self.url: Optional[str] = payload.get("url") + self.handle: Optional[str] = payload.get("handle") + self.total_calls: Optional[int] = deserialize.integer( + payload.get("total_calls") + ) + self.call_answer_score: Optional[float] = payload.get("call_answer_score") + self.call_state_percentage: Optional[str] = payload.get("call_state_percentage") + self.silent_calls_percentage: Optional[float] = payload.get( + "silent_calls_percentage" + ) + + self._solution = { + "report_id": report_id or self.report_id, + } + + self._context: Optional[InboundContext] = None + + @property + def _proxy(self) -> "InboundContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InboundContext for this InboundInstance + """ + if self._context is None: + self._context = InboundContext( + self._version, + report_id=self._solution["report_id"], + ) + return self._context + + def create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> "InboundInstance": + """ + Create the InboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created InboundInstance + """ + return self._proxy.create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request, + ) + + async def create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> "InboundInstance": + """ + Asynchronous coroutine to create the InboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created InboundInstance + """ + return await self._proxy.create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request, + ) + + def create_with_http_info( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the InboundInstance with HTTP info + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request, + ) + + async def create_with_http_info_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the InboundInstance with HTTP info + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_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 InboundContext(InstanceContext): + + class InsightsV2CreatePhoneNumbersReportRequest(object): + """ + :ivar time_range: + :ivar filters: + :ivar size: The number of max available top Phone Numbers to generate. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + InboundList.InsightsV2CreatePhoneNumbersReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[InboundList.PhoneNumberReportFilter]] = ( + payload.get("filters") + ) + self.size: Optional[int] = payload.get("size") + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + "size": self.size, + } + + class InsightsV2CreatePhoneNumbersReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class PhoneNumberReportFilter(object): + """ + :ivar key: The name of the filter + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + def __init__(self, version: Version, report_id: str): + """ + Initialize the InboundContext + + :param version: Version that contains the resource + :param report_id: A unique Report Id. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "report_id": report_id, + } + self._uri = "/Voice/Reports/PhoneNumbers/Inbound".format(**self._solution) + + def _create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> InboundInstance: + """ + Create the InboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created InboundInstance + """ + payload, _, _ = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + def create_with_http_info( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the InboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> InboundInstance: + """ + Asynchronous coroutine to create the InboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created InboundInstance + """ + payload, _, _ = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + async def create_with_http_info_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the InboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 InboundPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InboundInstance: + """ + Build an instance of InboundInstance + + :param payload: Payload response from the API + """ + + return InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InboundList(ListResource): + + class InsightsV2CreatePhoneNumbersReportRequest(object): + """ + :ivar time_range: + :ivar filters: + :ivar size: The number of max available top Phone Numbers to generate. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + InboundList.InsightsV2CreatePhoneNumbersReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[InboundList.PhoneNumberReportFilter]] = ( + payload.get("filters") + ) + self.size: Optional[int] = payload.get("size") + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + "size": self.size, + } + + class InsightsV2CreatePhoneNumbersReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class PhoneNumberReportFilter(object): + """ + :ivar key: The name of the filter + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + def __init__(self, version: Version, report_id: str): + """ + Initialize the InboundList + + :param version: Version that contains the resource + :param report_id: A unique Report Id. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "report_id": report_id, + } + self._uri = "/Voice/Reports/PhoneNumbers/Inbound/{report_id}".format( + **self._solution + ) + + def _create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> InboundInstance: + """ + Create the InboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created InboundInstance + """ + payload, _, _ = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + def create_with_http_info( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the InboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> InboundInstance: + """ + Asynchronously create the InboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created InboundInstance + """ + payload, _, _ = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + async def create_with_http_info_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the InboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InboundInstance]: + """ + Streams InboundInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InboundInstance]: + """ + Asynchronously streams InboundInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InboundInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InboundInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InboundInstance]: + """ + Lists InboundInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InboundInstance]: + """ + Asynchronously lists InboundInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InboundInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InboundInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InboundPage: + """ + Retrieve a single page of InboundInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InboundInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InboundPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InboundPage: + """ + Asynchronously retrieve a single page of InboundInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InboundInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InboundPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InboundPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InboundPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InboundPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InboundPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> InboundPage: + """ + Retrieve a specific page of InboundInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InboundInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InboundPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> InboundPage: + """ + Asynchronously retrieve a specific page of InboundInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InboundInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InboundPage(self._version, response, solution=self._solution) + + def get(self, report_id: str) -> InboundContext: + """ + Constructs a InboundContext + + :param report_id: A unique Report Id. + """ + return InboundContext(self._version, report_id=report_id) + + def __call__(self, report_id: str) -> InboundContext: + """ + Constructs a InboundContext + + :param report_id: A unique Report Id. + """ + return InboundContext(self._version, report_id=report_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/insights/v2/outbound.py b/twilio/rest/insights/v2/outbound.py new file mode 100644 index 0000000000..2774a09d08 --- /dev/null +++ b/twilio/rest/insights/v2/outbound.py @@ -0,0 +1,1227 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Sample/reference Twilio API. + This is the reference API for the rest-proxy server. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do 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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class OutboundInstance(InstanceResource): + + class CountyCarrierValueCarriers(object): + """ + :ivar carrier: The name of the carrier. + :ivar total_calls: Total number of outbound calls for the carrier in the country. + :ivar blocked_calls: Total number of blocked outbound calls for the carrier in the country. + :ivar blocked_calls_percentage: Percentage of blocked outbound calls for the carrier in the country. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[str] = payload.get("carrier") + self.total_calls: Optional[int] = payload.get("total_calls") + self.blocked_calls: Optional[int] = payload.get("blocked_calls") + self.blocked_calls_percentage: Optional[float] = payload.get( + "blocked_calls_percentage" + ) + + def to_dict(self): + return { + "carrier": self.carrier, + "total_calls": self.total_calls, + "blocked_calls": self.blocked_calls, + "blocked_calls_percentage": self.blocked_calls_percentage, + } + + class InsightsV2CreatePhoneNumbersReportRequest(object): + """ + :ivar time_range: + :ivar filters: + :ivar size: The number of max available top Phone Numbers to generate. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + InboundList.InsightsV2CreatePhoneNumbersReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[InboundList.PhoneNumberReportFilter]] = ( + payload.get("filters") + ) + self.size: Optional[int] = payload.get("size") + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + "size": self.size, + } + + class InsightsV2CreatePhoneNumbersReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class PhoneNumberReportFilter(object): + """ + :ivar key: The name of the filter + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportStatus(object): + CREATED = "created" + RUNNING = "running" + COMPLETED = "completed" + + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar report_id: The report identifier as Voice Insights Report TTID. + :ivar status: + :ivar request_meta: + :ivar url: The URL of this resource. + :ivar handle: Inbound phone number handle represented in the report. + :ivar total_calls: Total number of calls made with the given handle during the report period. + :ivar call_answer_score: The call answer score measures customers behavior to the delivered calls. The score is a value between 0 and 100, where 100 indicates that all calls were successfully answered. + :ivar call_state_percentage: + :ivar silent_calls_percentage: Percentage of inbound calls with silence tags over total outbound calls. A silent tag is indicative of a connectivity issue or muted audio. + :ivar calls_by_device_type: Number of calls made with each device type. `voip`, `mobile`, `landline`, `unknown` + :ivar answer_rate_device_type: Answer rate for each device type. `voip`, `mobile`, `landline`, `unknown` + :ivar blocked_calls_by_carrier: Percentage of blocked calls by carrier per country. + :ivar short_duration_calls_percentage: Percentage of completed outbound calls under 10 seconds (PSTN Short call tags); More than 15% is typically low trust measured. + :ivar long_duration_calls_percentage: Percentage of long duration calls ( >= 60 seconds) + :ivar potential_robocalls_percentage: Percentage of completed outbound calls to unassigned or unallocated phone numbers. + :ivar answering_machine_detection: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], report_id: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.report_id: Optional[str] = payload.get("report_id") + self.status: Optional["InboundInstance.str"] = payload.get("status") + self.request_meta: Optional[str] = payload.get("request_meta") + self.url: Optional[str] = payload.get("url") + self.handle: Optional[str] = payload.get("handle") + self.total_calls: Optional[int] = deserialize.integer( + payload.get("total_calls") + ) + self.call_answer_score: Optional[float] = payload.get("call_answer_score") + self.call_state_percentage: Optional[str] = payload.get("call_state_percentage") + self.silent_calls_percentage: Optional[float] = payload.get( + "silent_calls_percentage" + ) + self.calls_by_device_type: Optional[Dict[str, int]] = payload.get( + "calls_by_device_type" + ) + self.answer_rate_device_type: Optional[Dict[str, float]] = payload.get( + "answer_rate_device_type" + ) + self.blocked_calls_by_carrier: Optional[List[str]] = payload.get( + "blocked_calls_by_carrier" + ) + self.short_duration_calls_percentage: Optional[float] = payload.get( + "short_duration_calls_percentage" + ) + self.long_duration_calls_percentage: Optional[float] = payload.get( + "long_duration_calls_percentage" + ) + self.potential_robocalls_percentage: Optional[float] = payload.get( + "potential_robocalls_percentage" + ) + self.answering_machine_detection: Optional[str] = payload.get( + "answering_machine_detection" + ) + + self._solution = { + "report_id": report_id or self.report_id, + } + + self._context: Optional[OutboundContext] = None + + @property + def _proxy(self) -> "OutboundContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OutboundContext for this OutboundInstance + """ + if self._context is None: + self._context = OutboundContext( + self._version, + report_id=self._solution["report_id"], + ) + return self._context + + def create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> "OutboundInstance": + """ + Create the OutboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created OutboundInstance + """ + return self._proxy.create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request, + ) + + async def create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> "OutboundInstance": + """ + Asynchronous coroutine to create the OutboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created OutboundInstance + """ + return await self._proxy.create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request, + ) + + def create_with_http_info( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the OutboundInstance with HTTP info + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request, + ) + + async def create_with_http_info_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the OutboundInstance with HTTP info + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_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 OutboundContext(InstanceContext): + + class CountyCarrierValueCarriers(object): + """ + :ivar carrier: The name of the carrier. + :ivar total_calls: Total number of outbound calls for the carrier in the country. + :ivar blocked_calls: Total number of blocked outbound calls for the carrier in the country. + :ivar blocked_calls_percentage: Percentage of blocked outbound calls for the carrier in the country. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[str] = payload.get("carrier") + self.total_calls: Optional[int] = payload.get("total_calls") + self.blocked_calls: Optional[int] = payload.get("blocked_calls") + self.blocked_calls_percentage: Optional[float] = payload.get( + "blocked_calls_percentage" + ) + + def to_dict(self): + return { + "carrier": self.carrier, + "total_calls": self.total_calls, + "blocked_calls": self.blocked_calls, + "blocked_calls_percentage": self.blocked_calls_percentage, + } + + class InsightsV2CreatePhoneNumbersReportRequest(object): + """ + :ivar time_range: + :ivar filters: + :ivar size: The number of max available top Phone Numbers to generate. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + InboundList.InsightsV2CreatePhoneNumbersReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[InboundList.PhoneNumberReportFilter]] = ( + payload.get("filters") + ) + self.size: Optional[int] = payload.get("size") + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + "size": self.size, + } + + class InsightsV2CreatePhoneNumbersReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class PhoneNumberReportFilter(object): + """ + :ivar key: The name of the filter + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + def __init__(self, version: Version, report_id: str): + """ + Initialize the OutboundContext + + :param version: Version that contains the resource + :param report_id: A unique Report Id. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "report_id": report_id, + } + self._uri = "/Voice/Reports/PhoneNumbers/Outbound".format(**self._solution) + + def _create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> OutboundInstance: + """ + Create the OutboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created OutboundInstance + """ + payload, _, _ = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + def create_with_http_info( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the OutboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> OutboundInstance: + """ + Asynchronous coroutine to create the OutboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created OutboundInstance + """ + payload, _, _ = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + async def create_with_http_info_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the OutboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 OutboundPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> OutboundInstance: + """ + Build an instance of OutboundInstance + + :param payload: Payload response from the API + """ + + return OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class OutboundList(ListResource): + + class CountyCarrierValueCarriers(object): + """ + :ivar carrier: The name of the carrier. + :ivar total_calls: Total number of outbound calls for the carrier in the country. + :ivar blocked_calls: Total number of blocked outbound calls for the carrier in the country. + :ivar blocked_calls_percentage: Percentage of blocked outbound calls for the carrier in the country. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[str] = payload.get("carrier") + self.total_calls: Optional[int] = payload.get("total_calls") + self.blocked_calls: Optional[int] = payload.get("blocked_calls") + self.blocked_calls_percentage: Optional[float] = payload.get( + "blocked_calls_percentage" + ) + + def to_dict(self): + return { + "carrier": self.carrier, + "total_calls": self.total_calls, + "blocked_calls": self.blocked_calls, + "blocked_calls_percentage": self.blocked_calls_percentage, + } + + class InsightsV2CreatePhoneNumbersReportRequest(object): + """ + :ivar time_range: + :ivar filters: + :ivar size: The number of max available top Phone Numbers to generate. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + InboundList.InsightsV2CreatePhoneNumbersReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[InboundList.PhoneNumberReportFilter]] = ( + payload.get("filters") + ) + self.size: Optional[int] = payload.get("size") + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + "size": self.size, + } + + class InsightsV2CreatePhoneNumbersReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class PhoneNumberReportFilter(object): + """ + :ivar key: The name of the filter + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + def __init__(self, version: Version, report_id: str): + """ + Initialize the OutboundList + + :param version: Version that contains the resource + :param report_id: A unique Report Id. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "report_id": report_id, + } + self._uri = "/Voice/Reports/PhoneNumbers/Outbound/{report_id}".format( + **self._solution + ) + + def _create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> OutboundInstance: + """ + Create the OutboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created OutboundInstance + """ + payload, _, _ = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + def create_with_http_info( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the OutboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> OutboundInstance: + """ + Asynchronously create the OutboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created OutboundInstance + """ + payload, _, _ = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + async def create_with_http_info_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the OutboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OutboundInstance]: + """ + Streams OutboundInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[OutboundInstance]: + """ + Asynchronously streams OutboundInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OutboundInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OutboundInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OutboundInstance]: + """ + Lists OutboundInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OutboundInstance]: + """ + Asynchronously lists OutboundInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OutboundInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OutboundInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OutboundPage: + """ + Retrieve a single page of OutboundInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OutboundInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OutboundPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OutboundPage: + """ + Asynchronously retrieve a single page of OutboundInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OutboundInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OutboundPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OutboundPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OutboundPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OutboundPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OutboundPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> OutboundPage: + """ + Retrieve a specific page of OutboundInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OutboundInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OutboundPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> OutboundPage: + """ + Asynchronously retrieve a specific page of OutboundInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OutboundInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OutboundPage(self._version, response, solution=self._solution) + + def get(self, report_id: str) -> OutboundContext: + """ + Constructs a OutboundContext + + :param report_id: A unique Report Id. + """ + return OutboundContext(self._version, report_id=report_id) + + def __call__(self, report_id: str) -> OutboundContext: + """ + Constructs a OutboundContext + + :param report_id: A unique Report Id. + """ + return OutboundContext(self._version, report_id=report_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/insights/v2/report.py b/twilio/rest/insights/v2/report.py new file mode 100644 index 0000000000..fb7df212e9 --- /dev/null +++ b/twilio/rest/insights/v2/report.py @@ -0,0 +1,2199 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Sample/reference Twilio API. + This is the reference API for the rest-proxy server. + + NOTE: This class is auto generated by 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.api_response import ApiResponse +from twilio.base.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 ReportInstance(InstanceResource): + + class AccountReportAnsweringMachineDetection(object): + """ + :ivar total_calls: Total number of calls with answering machine detection enabled (AMD). + :ivar answered_by_human_percentage: Percentage of calls marked as answered by human. + :ivar answered_by_machine_percentage: Percentage of calls marked as answered by machined related like the following: `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `fax` + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_calls: Optional[int] = payload.get("total_calls") + self.answered_by_human_percentage: Optional[float] = payload.get( + "answered_by_human_percentage" + ) + self.answered_by_machine_percentage: Optional[float] = payload.get( + "answered_by_machine_percentage" + ) + + def to_dict(self): + return { + "total_calls": self.total_calls, + "answered_by_human_percentage": self.answered_by_human_percentage, + "answered_by_machine_percentage": self.answered_by_machine_percentage, + } + + class AccountReportCallDirection(object): + """ + :ivar outbound: Number of outbound calls + :ivar inbound: Number of inbound calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.outbound: Optional[int] = payload.get("outbound") + self.inbound: Optional[int] = payload.get("inbound") + + def to_dict(self): + return { + "outbound": self.outbound, + "inbound": self.inbound, + } + + class AccountReportCallState(object): + """ + :ivar completed: Number of completed calls + :ivar fail: Number of failed calls + :ivar busy: Number of busy calls + :ivar noanswer: Number of no-answer calls + :ivar canceled: Number of canceled calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.completed: Optional[int] = payload.get("completed") + self.fail: Optional[int] = payload.get("fail") + self.busy: Optional[int] = payload.get("busy") + self.noanswer: Optional[int] = payload.get("noanswer") + self.canceled: Optional[int] = payload.get("canceled") + + def to_dict(self): + return { + "completed": self.completed, + "fail": self.fail, + "busy": self.busy, + "noanswer": self.noanswer, + "canceled": self.canceled, + } + + class AccountReportCallType(object): + """ + :ivar carrier: Number of carrier calls + :ivar sip: Number of SIP calls + :ivar trunking: Number of trunking calls + :ivar client: Number of client calls + :ivar whatsapp: Number of WhatsApp Business calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[int] = payload.get("carrier") + self.sip: Optional[int] = payload.get("sip") + self.trunking: Optional[int] = payload.get("trunking") + self.client: Optional[int] = payload.get("client") + self.whatsapp: Optional[int] = payload.get("whatsapp") + + def to_dict(self): + return { + "carrier": self.carrier, + "sip": self.sip, + "trunking": self.trunking, + "client": self.client, + "whatsapp": self.whatsapp, + } + + class AccountReportKYT(object): + """ + :ivar outbound_carrier_calling: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.outbound_carrier_calling: Optional[ + AccountReportKYTOutboundCarrierCalling + ] = payload.get("outbound_carrier_calling") + + def to_dict(self): + return { + "outbound_carrier_calling": ( + self.outbound_carrier_calling.to_dict() + if self.outbound_carrier_calling is not None + else None + ), + } + + class AccountReportKYTOutboundCarrierCalling(object): + """ + :ivar unique_calling_numbers: Number of unique PSTN calling numbers to non-Twilio numbers during the report period. + :ivar unique_called_numbers: Number of unique non-Twilio PSTN called numbers during the report period. + :ivar blocked_calls_by_carrier: Percentage of blocked calls by carrier per country. + :ivar short_duration_calls_percentage: Percentage of completed outbound calls under 10 seconds (PSTN Short call tags); More than 15% is typically low trust measured. + :ivar long_duration_calls_percentage: Percentage of long duration calls ( >= 60 seconds) + :ivar potential_robocalls_percentage: Percentage of completed outbound calls to unassigned or unallocated phone numbers. + :ivar branded_calling: + :ivar voice_integrity: + :ivar stir_shaken: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_calling_numbers: Optional[int] = payload.get( + "unique_calling_numbers" + ) + self.unique_called_numbers: Optional[int] = payload.get( + "unique_called_numbers" + ) + self.blocked_calls_by_carrier: Optional[List[CountyCarrierValue]] = ( + payload.get("blocked_calls_by_carrier") + ) + self.short_duration_calls_percentage: Optional[float] = payload.get( + "short_duration_calls_percentage" + ) + self.long_duration_calls_percentage: Optional[float] = payload.get( + "long_duration_calls_percentage" + ) + self.potential_robocalls_percentage: Optional[float] = payload.get( + "potential_robocalls_percentage" + ) + self.branded_calling: Optional[BrandedCalling] = payload.get( + "branded_calling" + ) + self.voice_integrity: Optional[VoiceIntegrity] = payload.get( + "voice_integrity" + ) + self.stir_shaken: Optional[StirShaken] = payload.get("stir_shaken") + + def to_dict(self): + return { + "unique_calling_numbers": self.unique_calling_numbers, + "unique_called_numbers": self.unique_called_numbers, + "blocked_calls_by_carrier": ( + [ + blocked_calls_by_carrier.to_dict() + for blocked_calls_by_carrier in self.blocked_calls_by_carrier + ] + if self.blocked_calls_by_carrier is not None + else None + ), + "short_duration_calls_percentage": self.short_duration_calls_percentage, + "long_duration_calls_percentage": self.long_duration_calls_percentage, + "potential_robocalls_percentage": self.potential_robocalls_percentage, + "branded_calling": ( + self.branded_calling.to_dict() + if self.branded_calling is not None + else None + ), + "voice_integrity": ( + self.voice_integrity.to_dict() + if self.voice_integrity is not None + else None + ), + "stir_shaken": ( + self.stir_shaken.to_dict() if self.stir_shaken is not None else None + ), + } + + class AccountReportNetworkIssues(object): + """ + :ivar sdk: + :ivar twilio_gateway: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sdk: Optional[AccountReportNetworkIssuesSdk] = payload.get("sdk") + self.twilio_gateway: Optional[AccountReportNetworkIssuesTwilioGateway] = ( + payload.get("twilio_gateway") + ) + + def to_dict(self): + return { + "sdk": self.sdk.to_dict() if self.sdk is not None else None, + "twilio_gateway": ( + self.twilio_gateway.to_dict() + if self.twilio_gateway is not None + else None + ), + } + + class AccountReportNetworkIssuesSdk(object): + """ + :ivar ice_failures_percentage: Percentage of ICE connection failure tag that ICE candidates have failed to find compatible connection. + :ivar high_latency_percentage: Percentage of calls with high latency. + :ivar high_packet_loss_percentage: Percentage of calls with high packet loss. + :ivar high_jitter_percentage: Percentage of calls with high jitter. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.ice_failures_percentage: Optional[float] = payload.get( + "ice_failures_percentage" + ) + self.high_latency_percentage: Optional[float] = payload.get( + "high_latency_percentage" + ) + self.high_packet_loss_percentage: Optional[float] = payload.get( + "high_packet_loss_percentage" + ) + self.high_jitter_percentage: Optional[float] = payload.get( + "high_jitter_percentage" + ) + + def to_dict(self): + return { + "ice_failures_percentage": self.ice_failures_percentage, + "high_latency_percentage": self.high_latency_percentage, + "high_packet_loss_percentage": self.high_packet_loss_percentage, + "high_jitter_percentage": self.high_jitter_percentage, + } + + class AccountReportNetworkIssuesTwilioGateway(object): + """ + :ivar high_latency_percentage: Percentage of calls with high latency. + :ivar high_packet_loss_percentage: Percentage of calls with high packet loss. + :ivar high_jitter_percentage: Percentage of calls with high jitter. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.high_latency_percentage: Optional[float] = payload.get( + "high_latency_percentage" + ) + self.high_packet_loss_percentage: Optional[float] = payload.get( + "high_packet_loss_percentage" + ) + self.high_jitter_percentage: Optional[float] = payload.get( + "high_jitter_percentage" + ) + + def to_dict(self): + return { + "high_latency_percentage": self.high_latency_percentage, + "high_packet_loss_percentage": self.high_packet_loss_percentage, + "high_jitter_percentage": self.high_jitter_percentage, + } + + class BrandedCalling(object): + """ + :ivar total_branded_calls: Total number of Branded bundled calls. + :ivar percent_branded_calls: Percentage of Branded bundled calls over total outbound calls. + :ivar answer_rate: Answer rate for Branded bundled calls. + :ivar human_answer_rate: Rate of Branded bundled calls that were answered by Human. + :ivar engagement_rate: Engagement Rate for Branded bundled calls where its call length is longer than 60 seconds. + :ivar by_use_case: Details of branded calls by use case. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_branded_calls: Optional[int] = payload.get("total_branded_calls") + self.percent_branded_calls: Optional[float] = payload.get( + "percent_branded_calls" + ) + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + self.engagement_rate: Optional[float] = payload.get("engagement_rate") + self.by_use_case: Optional[List[BrandedUseCaseDetail]] = payload.get( + "by_use_case" + ) + + def to_dict(self): + return { + "total_branded_calls": self.total_branded_calls, + "percent_branded_calls": self.percent_branded_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + "engagement_rate": self.engagement_rate, + "by_use_case": ( + [by_use_case.to_dict() for by_use_case in self.by_use_case] + if self.by_use_case is not None + else None + ), + } + + class BrandedUseCaseDetail(object): + """ + :ivar use_case: The name of supported use case for Branded calls. + :ivar enabled_phonenumbers: The number of phone numbers enabled Branded calls. + :ivar total_calls: The number of total outbound calls for the use case. + :ivar answer_rate: Answer rate per each use case for Branded bundled calls. + :ivar human_answer_rate: Rate of Branded bundled calls that were answered by Human per each use case for Branded bundled calls. + :ivar engagement_rate: Engagement Rate for Branded bundled calls where its call length is longer than 60 seconds per each use case for Branded bundled calls. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.use_case: Optional[str] = payload.get("use_case") + self.enabled_phonenumbers: Optional[int] = payload.get( + "enabled_phonenumbers" + ) + self.total_calls: Optional[int] = payload.get("total_calls") + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + self.engagement_rate: Optional[float] = payload.get("engagement_rate") + + def to_dict(self): + return { + "use_case": self.use_case, + "enabled_phonenumbers": self.enabled_phonenumbers, + "total_calls": self.total_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + "engagement_rate": self.engagement_rate, + } + + class CountyCarrierValueCarriers(object): + """ + :ivar carrier: The name of the carrier. + :ivar total_calls: Total number of outbound calls for the carrier in the country. + :ivar blocked_calls: Total number of blocked outbound calls for the carrier in the country. + :ivar blocked_calls_percentage: Percentage of blocked outbound calls for the carrier in the country. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[str] = payload.get("carrier") + self.total_calls: Optional[int] = payload.get("total_calls") + self.blocked_calls: Optional[int] = payload.get("blocked_calls") + self.blocked_calls_percentage: Optional[float] = payload.get( + "blocked_calls_percentage" + ) + + def to_dict(self): + return { + "carrier": self.carrier, + "total_calls": self.total_calls, + "blocked_calls": self.blocked_calls, + "blocked_calls_percentage": self.blocked_calls_percentage, + } + + class InsightsV2CreateAccountReportRequest(object): + """ + :ivar time_range: + :ivar filters: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + ReportList.InsightsV2CreateAccountReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[ReportList.ReportFilter]] = payload.get( + "filters" + ) + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + } + + class InsightsV2CreateAccountReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class StirShaken(object): + """ + :ivar call_count: + :ivar percentage: + :ivar answer_rate: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.call_count: Optional[StirShakenCallCount] = payload.get("call_count") + self.percentage: Optional[StirShakenPercentage] = payload.get("percentage") + self.answer_rate: Optional[StirShakenAnswerRate] = payload.get( + "answer_rate" + ) + + def to_dict(self): + return { + "call_count": ( + self.call_count.to_dict() if self.call_count is not None else None + ), + "percentage": ( + self.percentage.to_dict() if self.percentage is not None else None + ), + "answer_rate": ( + self.answer_rate.to_dict() if self.answer_rate is not None else None + ), + } + + class StirShakenAnswerRate(object): + """ + :ivar stsh_a: Answer rate for Stir Shaken category A. + :ivar stsh_b: Answer rate for Stir Shaken category B. + :ivar stsh_c: Answer rate for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[float] = payload.get("stsh_a") + self.stsh_b: Optional[float] = payload.get("stsh_b") + self.stsh_c: Optional[float] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class StirShakenCallCount(object): + """ + :ivar stsh_a: Total number of calls for Stir Shaken category A. + :ivar stsh_b: Total number of calls for Stir Shaken category B. + :ivar stsh_c: Total number of calls for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[int] = payload.get("stsh_a") + self.stsh_b: Optional[int] = payload.get("stsh_b") + self.stsh_c: Optional[int] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class StirShakenPercentage(object): + """ + :ivar stsh_a: Percentage of calls for Stir Shaken category A. + :ivar stsh_b: Percentage of calls for Stir Shaken category B. + :ivar stsh_c: Percentage of calls for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[float] = payload.get("stsh_a") + self.stsh_b: Optional[float] = payload.get("stsh_b") + self.stsh_c: Optional[float] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class VoiceIntegrity(object): + """ + :ivar enabled_calls: Total number of calls with Voice Integrity enabled. + :ivar enabled_percentage: Percentage of calls with Voice Integrity enabled. + :ivar calls_per_bundle: Number of calls per Voice Integrity enabled Bundle Sid. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.enabled_calls: Optional[int] = payload.get("enabled_calls") + self.enabled_percentage: Optional[float] = payload.get("enabled_percentage") + self.calls_per_bundle: Optional[List[VoiceIntegrityCallsPerBundle]] = ( + payload.get("calls_per_bundle") + ) + + def to_dict(self): + return { + "enabled_calls": self.enabled_calls, + "enabled_percentage": self.enabled_percentage, + "calls_per_bundle": ( + [ + calls_per_bundle.to_dict() + for calls_per_bundle in self.calls_per_bundle + ] + if self.calls_per_bundle is not None + else None + ), + } + + class VoiceIntegrityCallsPerBundle(object): + """ + :ivar bundle_sid: Voice Integrity Approved Profile Sid. + :ivar enabled_phonenumbers: The number of Voice Integrity enabled and registered phone numbers per Bundle Sid. + :ivar total_calls: The number of outbound calls on Voice Integrity enabled and registered number per Bundle Sid. + :ivar answer_rate: Answer rate for calls on Voice Integrity enabled and registered number per Bundle Sid. + :ivar human_answer_rate: Rate for calls on Voice Integrity enabled and registered number per Bundle Sid that were answered by Human per each use case for Branded bundled calls. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.enabled_phonenumbers: Optional[int] = payload.get( + "enabled_phonenumbers" + ) + self.total_calls: Optional[int] = payload.get("total_calls") + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + + def to_dict(self): + return { + "bundle_sid": self.bundle_sid, + "enabled_phonenumbers": self.enabled_phonenumbers, + "total_calls": self.total_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + } + + class ReportStatus(object): + CREATED = "created" + RUNNING = "running" + COMPLETED = "completed" + + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar report_id: The report identifier as Voice Insights Report TTID. + :ivar status: + :ivar request_meta: + :ivar url: The URL of this resource. + :ivar handle: Inbound phone number handle represented in the report. + :ivar total_calls: Total number of calls made with the given handle during the report period. + :ivar call_answer_score: The call answer score measures customers behavior to the delivered calls. The score is a value between 0 and 100, where 100 indicates that all calls were successfully answered. + :ivar call_state_percentage: + :ivar silent_calls_percentage: Percentage of inbound calls with silence tags over total outbound calls. A silent tag is indicative of a connectivity issue or muted audio. + :ivar calls_by_device_type: Number of calls made with each device type. `voip`, `mobile`, `landline`, `unknown` + :ivar answer_rate_device_type: Answer rate for each device type. `voip`, `mobile`, `landline`, `unknown` + :ivar blocked_calls_by_carrier: Percentage of blocked calls by carrier per country. + :ivar short_duration_calls_percentage: Percentage of completed outbound calls under 10 seconds (PSTN Short call tags); More than 15% is typically low trust measured. + :ivar long_duration_calls_percentage: Percentage of long duration calls ( >= 60 seconds) + :ivar potential_robocalls_percentage: Percentage of completed outbound calls to unassigned or unallocated phone numbers. + :ivar answering_machine_detection: + :ivar report: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], report_id: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.report_id: Optional[str] = payload.get("report_id") + self.status: Optional["InboundInstance.str"] = payload.get("status") + self.request_meta: Optional[str] = payload.get("request_meta") + self.url: Optional[str] = payload.get("url") + self.handle: Optional[str] = payload.get("handle") + self.total_calls: Optional[int] = deserialize.integer( + payload.get("total_calls") + ) + self.call_answer_score: Optional[float] = payload.get("call_answer_score") + self.call_state_percentage: Optional[str] = payload.get("call_state_percentage") + self.silent_calls_percentage: Optional[float] = payload.get( + "silent_calls_percentage" + ) + self.calls_by_device_type: Optional[Dict[str, int]] = payload.get( + "calls_by_device_type" + ) + self.answer_rate_device_type: Optional[Dict[str, float]] = payload.get( + "answer_rate_device_type" + ) + self.blocked_calls_by_carrier: Optional[List[str]] = payload.get( + "blocked_calls_by_carrier" + ) + self.short_duration_calls_percentage: Optional[float] = payload.get( + "short_duration_calls_percentage" + ) + self.long_duration_calls_percentage: Optional[float] = payload.get( + "long_duration_calls_percentage" + ) + self.potential_robocalls_percentage: Optional[float] = payload.get( + "potential_robocalls_percentage" + ) + self.answering_machine_detection: Optional[str] = payload.get( + "answering_machine_detection" + ) + self.report: Optional[str] = payload.get("report") + + self._solution = { + "report_id": report_id or self.report_id, + } + + self._context: Optional[ReportContext] = None + + @property + def _proxy(self) -> "ReportContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ReportContext for this ReportInstance + """ + if self._context is None: + self._context = ReportContext( + self._version, + report_id=self._solution["report_id"], + ) + return self._context + + def create( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> "ReportInstance": + """ + Create the ReportInstance + + :param insights_v2_create_account_report_request: + + :returns: The created ReportInstance + """ + return self._proxy.create( + insights_v2_create_account_report_request=insights_v2_create_account_report_request, + ) + + async def create_async( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> "ReportInstance": + """ + Asynchronous coroutine to create the ReportInstance + + :param insights_v2_create_account_report_request: + + :returns: The created ReportInstance + """ + return await self._proxy.create_async( + insights_v2_create_account_report_request=insights_v2_create_account_report_request, + ) + + def create_with_http_info( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the ReportInstance with HTTP info + + :param insights_v2_create_account_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + insights_v2_create_account_report_request=insights_v2_create_account_report_request, + ) + + async def create_with_http_info_async( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the ReportInstance with HTTP info + + :param insights_v2_create_account_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + insights_v2_create_account_report_request=insights_v2_create_account_report_request, + ) + + def fetch(self) -> "ReportInstance": + """ + Fetch the ReportInstance + + + :returns: The fetched ReportInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ReportInstance": + """ + Asynchronous coroutine to fetch the ReportInstance + + + :returns: The fetched ReportInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ReportInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ReportInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 ReportContext(InstanceContext): + + class AccountReportAnsweringMachineDetection(object): + """ + :ivar total_calls: Total number of calls with answering machine detection enabled (AMD). + :ivar answered_by_human_percentage: Percentage of calls marked as answered by human. + :ivar answered_by_machine_percentage: Percentage of calls marked as answered by machined related like the following: `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `fax` + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_calls: Optional[int] = payload.get("total_calls") + self.answered_by_human_percentage: Optional[float] = payload.get( + "answered_by_human_percentage" + ) + self.answered_by_machine_percentage: Optional[float] = payload.get( + "answered_by_machine_percentage" + ) + + def to_dict(self): + return { + "total_calls": self.total_calls, + "answered_by_human_percentage": self.answered_by_human_percentage, + "answered_by_machine_percentage": self.answered_by_machine_percentage, + } + + class AccountReportCallDirection(object): + """ + :ivar outbound: Number of outbound calls + :ivar inbound: Number of inbound calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.outbound: Optional[int] = payload.get("outbound") + self.inbound: Optional[int] = payload.get("inbound") + + def to_dict(self): + return { + "outbound": self.outbound, + "inbound": self.inbound, + } + + class AccountReportCallState(object): + """ + :ivar completed: Number of completed calls + :ivar fail: Number of failed calls + :ivar busy: Number of busy calls + :ivar noanswer: Number of no-answer calls + :ivar canceled: Number of canceled calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.completed: Optional[int] = payload.get("completed") + self.fail: Optional[int] = payload.get("fail") + self.busy: Optional[int] = payload.get("busy") + self.noanswer: Optional[int] = payload.get("noanswer") + self.canceled: Optional[int] = payload.get("canceled") + + def to_dict(self): + return { + "completed": self.completed, + "fail": self.fail, + "busy": self.busy, + "noanswer": self.noanswer, + "canceled": self.canceled, + } + + class AccountReportCallType(object): + """ + :ivar carrier: Number of carrier calls + :ivar sip: Number of SIP calls + :ivar trunking: Number of trunking calls + :ivar client: Number of client calls + :ivar whatsapp: Number of WhatsApp Business calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[int] = payload.get("carrier") + self.sip: Optional[int] = payload.get("sip") + self.trunking: Optional[int] = payload.get("trunking") + self.client: Optional[int] = payload.get("client") + self.whatsapp: Optional[int] = payload.get("whatsapp") + + def to_dict(self): + return { + "carrier": self.carrier, + "sip": self.sip, + "trunking": self.trunking, + "client": self.client, + "whatsapp": self.whatsapp, + } + + class AccountReportKYT(object): + """ + :ivar outbound_carrier_calling: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.outbound_carrier_calling: Optional[ + AccountReportKYTOutboundCarrierCalling + ] = payload.get("outbound_carrier_calling") + + def to_dict(self): + return { + "outbound_carrier_calling": ( + self.outbound_carrier_calling.to_dict() + if self.outbound_carrier_calling is not None + else None + ), + } + + class AccountReportKYTOutboundCarrierCalling(object): + """ + :ivar unique_calling_numbers: Number of unique PSTN calling numbers to non-Twilio numbers during the report period. + :ivar unique_called_numbers: Number of unique non-Twilio PSTN called numbers during the report period. + :ivar blocked_calls_by_carrier: Percentage of blocked calls by carrier per country. + :ivar short_duration_calls_percentage: Percentage of completed outbound calls under 10 seconds (PSTN Short call tags); More than 15% is typically low trust measured. + :ivar long_duration_calls_percentage: Percentage of long duration calls ( >= 60 seconds) + :ivar potential_robocalls_percentage: Percentage of completed outbound calls to unassigned or unallocated phone numbers. + :ivar branded_calling: + :ivar voice_integrity: + :ivar stir_shaken: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_calling_numbers: Optional[int] = payload.get( + "unique_calling_numbers" + ) + self.unique_called_numbers: Optional[int] = payload.get( + "unique_called_numbers" + ) + self.blocked_calls_by_carrier: Optional[List[CountyCarrierValue]] = ( + payload.get("blocked_calls_by_carrier") + ) + self.short_duration_calls_percentage: Optional[float] = payload.get( + "short_duration_calls_percentage" + ) + self.long_duration_calls_percentage: Optional[float] = payload.get( + "long_duration_calls_percentage" + ) + self.potential_robocalls_percentage: Optional[float] = payload.get( + "potential_robocalls_percentage" + ) + self.branded_calling: Optional[BrandedCalling] = payload.get( + "branded_calling" + ) + self.voice_integrity: Optional[VoiceIntegrity] = payload.get( + "voice_integrity" + ) + self.stir_shaken: Optional[StirShaken] = payload.get("stir_shaken") + + def to_dict(self): + return { + "unique_calling_numbers": self.unique_calling_numbers, + "unique_called_numbers": self.unique_called_numbers, + "blocked_calls_by_carrier": ( + [ + blocked_calls_by_carrier.to_dict() + for blocked_calls_by_carrier in self.blocked_calls_by_carrier + ] + if self.blocked_calls_by_carrier is not None + else None + ), + "short_duration_calls_percentage": self.short_duration_calls_percentage, + "long_duration_calls_percentage": self.long_duration_calls_percentage, + "potential_robocalls_percentage": self.potential_robocalls_percentage, + "branded_calling": ( + self.branded_calling.to_dict() + if self.branded_calling is not None + else None + ), + "voice_integrity": ( + self.voice_integrity.to_dict() + if self.voice_integrity is not None + else None + ), + "stir_shaken": ( + self.stir_shaken.to_dict() if self.stir_shaken is not None else None + ), + } + + class AccountReportNetworkIssues(object): + """ + :ivar sdk: + :ivar twilio_gateway: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sdk: Optional[AccountReportNetworkIssuesSdk] = payload.get("sdk") + self.twilio_gateway: Optional[AccountReportNetworkIssuesTwilioGateway] = ( + payload.get("twilio_gateway") + ) + + def to_dict(self): + return { + "sdk": self.sdk.to_dict() if self.sdk is not None else None, + "twilio_gateway": ( + self.twilio_gateway.to_dict() + if self.twilio_gateway is not None + else None + ), + } + + class AccountReportNetworkIssuesSdk(object): + """ + :ivar ice_failures_percentage: Percentage of ICE connection failure tag that ICE candidates have failed to find compatible connection. + :ivar high_latency_percentage: Percentage of calls with high latency. + :ivar high_packet_loss_percentage: Percentage of calls with high packet loss. + :ivar high_jitter_percentage: Percentage of calls with high jitter. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.ice_failures_percentage: Optional[float] = payload.get( + "ice_failures_percentage" + ) + self.high_latency_percentage: Optional[float] = payload.get( + "high_latency_percentage" + ) + self.high_packet_loss_percentage: Optional[float] = payload.get( + "high_packet_loss_percentage" + ) + self.high_jitter_percentage: Optional[float] = payload.get( + "high_jitter_percentage" + ) + + def to_dict(self): + return { + "ice_failures_percentage": self.ice_failures_percentage, + "high_latency_percentage": self.high_latency_percentage, + "high_packet_loss_percentage": self.high_packet_loss_percentage, + "high_jitter_percentage": self.high_jitter_percentage, + } + + class AccountReportNetworkIssuesTwilioGateway(object): + """ + :ivar high_latency_percentage: Percentage of calls with high latency. + :ivar high_packet_loss_percentage: Percentage of calls with high packet loss. + :ivar high_jitter_percentage: Percentage of calls with high jitter. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.high_latency_percentage: Optional[float] = payload.get( + "high_latency_percentage" + ) + self.high_packet_loss_percentage: Optional[float] = payload.get( + "high_packet_loss_percentage" + ) + self.high_jitter_percentage: Optional[float] = payload.get( + "high_jitter_percentage" + ) + + def to_dict(self): + return { + "high_latency_percentage": self.high_latency_percentage, + "high_packet_loss_percentage": self.high_packet_loss_percentage, + "high_jitter_percentage": self.high_jitter_percentage, + } + + class BrandedCalling(object): + """ + :ivar total_branded_calls: Total number of Branded bundled calls. + :ivar percent_branded_calls: Percentage of Branded bundled calls over total outbound calls. + :ivar answer_rate: Answer rate for Branded bundled calls. + :ivar human_answer_rate: Rate of Branded bundled calls that were answered by Human. + :ivar engagement_rate: Engagement Rate for Branded bundled calls where its call length is longer than 60 seconds. + :ivar by_use_case: Details of branded calls by use case. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_branded_calls: Optional[int] = payload.get("total_branded_calls") + self.percent_branded_calls: Optional[float] = payload.get( + "percent_branded_calls" + ) + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + self.engagement_rate: Optional[float] = payload.get("engagement_rate") + self.by_use_case: Optional[List[BrandedUseCaseDetail]] = payload.get( + "by_use_case" + ) + + def to_dict(self): + return { + "total_branded_calls": self.total_branded_calls, + "percent_branded_calls": self.percent_branded_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + "engagement_rate": self.engagement_rate, + "by_use_case": ( + [by_use_case.to_dict() for by_use_case in self.by_use_case] + if self.by_use_case is not None + else None + ), + } + + class BrandedUseCaseDetail(object): + """ + :ivar use_case: The name of supported use case for Branded calls. + :ivar enabled_phonenumbers: The number of phone numbers enabled Branded calls. + :ivar total_calls: The number of total outbound calls for the use case. + :ivar answer_rate: Answer rate per each use case for Branded bundled calls. + :ivar human_answer_rate: Rate of Branded bundled calls that were answered by Human per each use case for Branded bundled calls. + :ivar engagement_rate: Engagement Rate for Branded bundled calls where its call length is longer than 60 seconds per each use case for Branded bundled calls. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.use_case: Optional[str] = payload.get("use_case") + self.enabled_phonenumbers: Optional[int] = payload.get( + "enabled_phonenumbers" + ) + self.total_calls: Optional[int] = payload.get("total_calls") + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + self.engagement_rate: Optional[float] = payload.get("engagement_rate") + + def to_dict(self): + return { + "use_case": self.use_case, + "enabled_phonenumbers": self.enabled_phonenumbers, + "total_calls": self.total_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + "engagement_rate": self.engagement_rate, + } + + class CountyCarrierValueCarriers(object): + """ + :ivar carrier: The name of the carrier. + :ivar total_calls: Total number of outbound calls for the carrier in the country. + :ivar blocked_calls: Total number of blocked outbound calls for the carrier in the country. + :ivar blocked_calls_percentage: Percentage of blocked outbound calls for the carrier in the country. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[str] = payload.get("carrier") + self.total_calls: Optional[int] = payload.get("total_calls") + self.blocked_calls: Optional[int] = payload.get("blocked_calls") + self.blocked_calls_percentage: Optional[float] = payload.get( + "blocked_calls_percentage" + ) + + def to_dict(self): + return { + "carrier": self.carrier, + "total_calls": self.total_calls, + "blocked_calls": self.blocked_calls, + "blocked_calls_percentage": self.blocked_calls_percentage, + } + + class InsightsV2CreateAccountReportRequest(object): + """ + :ivar time_range: + :ivar filters: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + ReportList.InsightsV2CreateAccountReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[ReportList.ReportFilter]] = payload.get( + "filters" + ) + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + } + + class InsightsV2CreateAccountReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class StirShaken(object): + """ + :ivar call_count: + :ivar percentage: + :ivar answer_rate: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.call_count: Optional[StirShakenCallCount] = payload.get("call_count") + self.percentage: Optional[StirShakenPercentage] = payload.get("percentage") + self.answer_rate: Optional[StirShakenAnswerRate] = payload.get( + "answer_rate" + ) + + def to_dict(self): + return { + "call_count": ( + self.call_count.to_dict() if self.call_count is not None else None + ), + "percentage": ( + self.percentage.to_dict() if self.percentage is not None else None + ), + "answer_rate": ( + self.answer_rate.to_dict() if self.answer_rate is not None else None + ), + } + + class StirShakenAnswerRate(object): + """ + :ivar stsh_a: Answer rate for Stir Shaken category A. + :ivar stsh_b: Answer rate for Stir Shaken category B. + :ivar stsh_c: Answer rate for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[float] = payload.get("stsh_a") + self.stsh_b: Optional[float] = payload.get("stsh_b") + self.stsh_c: Optional[float] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class StirShakenCallCount(object): + """ + :ivar stsh_a: Total number of calls for Stir Shaken category A. + :ivar stsh_b: Total number of calls for Stir Shaken category B. + :ivar stsh_c: Total number of calls for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[int] = payload.get("stsh_a") + self.stsh_b: Optional[int] = payload.get("stsh_b") + self.stsh_c: Optional[int] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class StirShakenPercentage(object): + """ + :ivar stsh_a: Percentage of calls for Stir Shaken category A. + :ivar stsh_b: Percentage of calls for Stir Shaken category B. + :ivar stsh_c: Percentage of calls for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[float] = payload.get("stsh_a") + self.stsh_b: Optional[float] = payload.get("stsh_b") + self.stsh_c: Optional[float] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class VoiceIntegrity(object): + """ + :ivar enabled_calls: Total number of calls with Voice Integrity enabled. + :ivar enabled_percentage: Percentage of calls with Voice Integrity enabled. + :ivar calls_per_bundle: Number of calls per Voice Integrity enabled Bundle Sid. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.enabled_calls: Optional[int] = payload.get("enabled_calls") + self.enabled_percentage: Optional[float] = payload.get("enabled_percentage") + self.calls_per_bundle: Optional[List[VoiceIntegrityCallsPerBundle]] = ( + payload.get("calls_per_bundle") + ) + + def to_dict(self): + return { + "enabled_calls": self.enabled_calls, + "enabled_percentage": self.enabled_percentage, + "calls_per_bundle": ( + [ + calls_per_bundle.to_dict() + for calls_per_bundle in self.calls_per_bundle + ] + if self.calls_per_bundle is not None + else None + ), + } + + class VoiceIntegrityCallsPerBundle(object): + """ + :ivar bundle_sid: Voice Integrity Approved Profile Sid. + :ivar enabled_phonenumbers: The number of Voice Integrity enabled and registered phone numbers per Bundle Sid. + :ivar total_calls: The number of outbound calls on Voice Integrity enabled and registered number per Bundle Sid. + :ivar answer_rate: Answer rate for calls on Voice Integrity enabled and registered number per Bundle Sid. + :ivar human_answer_rate: Rate for calls on Voice Integrity enabled and registered number per Bundle Sid that were answered by Human per each use case for Branded bundled calls. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.enabled_phonenumbers: Optional[int] = payload.get( + "enabled_phonenumbers" + ) + self.total_calls: Optional[int] = payload.get("total_calls") + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + + def to_dict(self): + return { + "bundle_sid": self.bundle_sid, + "enabled_phonenumbers": self.enabled_phonenumbers, + "total_calls": self.total_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + } + + def __init__(self, version: Version, report_id: str): + """ + Initialize the ReportContext + + :param version: Version that contains the resource + :param report_id: A unique request id. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "report_id": report_id, + } + self._uri = "/Voice/Reports/{report_id}".format(**self._solution) + + def _create( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_account_report_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> ReportInstance: + """ + Create the ReportInstance + + :param insights_v2_create_account_report_request: + + :returns: The created ReportInstance + """ + payload, _, _ = self._create( + insights_v2_create_account_report_request=insights_v2_create_account_report_request + ) + return ReportInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + def create_with_http_info( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the ReportInstance and return response metadata + + :param insights_v2_create_account_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + insights_v2_create_account_report_request=insights_v2_create_account_report_request + ) + instance = ReportInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_account_report_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> ReportInstance: + """ + Asynchronous coroutine to create the ReportInstance + + :param insights_v2_create_account_report_request: + + :returns: The created ReportInstance + """ + payload, _, _ = await self._create_async( + insights_v2_create_account_report_request=insights_v2_create_account_report_request + ) + return ReportInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + async def create_with_http_info_async( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the ReportInstance and return response metadata + + :param insights_v2_create_account_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + insights_v2_create_account_report_request=insights_v2_create_account_report_request + ) + instance = ReportInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ReportInstance: + """ + Fetch the ReportInstance + + + :returns: The fetched ReportInstance + """ + payload, _, _ = self._fetch() + return ReportInstance( + self._version, + payload, + report_id=self._solution["report_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ReportInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ReportInstance( + self._version, + payload, + report_id=self._solution["report_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ReportInstance: + """ + Asynchronous coroutine to fetch the ReportInstance + + + :returns: The fetched ReportInstance + """ + payload, _, _ = await self._fetch_async() + return ReportInstance( + self._version, + payload, + report_id=self._solution["report_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ReportInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ReportInstance( + self._version, + payload, + report_id=self._solution["report_id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 ReportList(ListResource): + + class AccountReportAnsweringMachineDetection(object): + """ + :ivar total_calls: Total number of calls with answering machine detection enabled (AMD). + :ivar answered_by_human_percentage: Percentage of calls marked as answered by human. + :ivar answered_by_machine_percentage: Percentage of calls marked as answered by machined related like the following: `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `fax` + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_calls: Optional[int] = payload.get("total_calls") + self.answered_by_human_percentage: Optional[float] = payload.get( + "answered_by_human_percentage" + ) + self.answered_by_machine_percentage: Optional[float] = payload.get( + "answered_by_machine_percentage" + ) + + def to_dict(self): + return { + "total_calls": self.total_calls, + "answered_by_human_percentage": self.answered_by_human_percentage, + "answered_by_machine_percentage": self.answered_by_machine_percentage, + } + + class AccountReportCallDirection(object): + """ + :ivar outbound: Number of outbound calls + :ivar inbound: Number of inbound calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.outbound: Optional[int] = payload.get("outbound") + self.inbound: Optional[int] = payload.get("inbound") + + def to_dict(self): + return { + "outbound": self.outbound, + "inbound": self.inbound, + } + + class AccountReportCallState(object): + """ + :ivar completed: Number of completed calls + :ivar fail: Number of failed calls + :ivar busy: Number of busy calls + :ivar noanswer: Number of no-answer calls + :ivar canceled: Number of canceled calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.completed: Optional[int] = payload.get("completed") + self.fail: Optional[int] = payload.get("fail") + self.busy: Optional[int] = payload.get("busy") + self.noanswer: Optional[int] = payload.get("noanswer") + self.canceled: Optional[int] = payload.get("canceled") + + def to_dict(self): + return { + "completed": self.completed, + "fail": self.fail, + "busy": self.busy, + "noanswer": self.noanswer, + "canceled": self.canceled, + } + + class AccountReportCallType(object): + """ + :ivar carrier: Number of carrier calls + :ivar sip: Number of SIP calls + :ivar trunking: Number of trunking calls + :ivar client: Number of client calls + :ivar whatsapp: Number of WhatsApp Business calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[int] = payload.get("carrier") + self.sip: Optional[int] = payload.get("sip") + self.trunking: Optional[int] = payload.get("trunking") + self.client: Optional[int] = payload.get("client") + self.whatsapp: Optional[int] = payload.get("whatsapp") + + def to_dict(self): + return { + "carrier": self.carrier, + "sip": self.sip, + "trunking": self.trunking, + "client": self.client, + "whatsapp": self.whatsapp, + } + + class AccountReportKYT(object): + """ + :ivar outbound_carrier_calling: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.outbound_carrier_calling: Optional[ + AccountReportKYTOutboundCarrierCalling + ] = payload.get("outbound_carrier_calling") + + def to_dict(self): + return { + "outbound_carrier_calling": ( + self.outbound_carrier_calling.to_dict() + if self.outbound_carrier_calling is not None + else None + ), + } + + class AccountReportKYTOutboundCarrierCalling(object): + """ + :ivar unique_calling_numbers: Number of unique PSTN calling numbers to non-Twilio numbers during the report period. + :ivar unique_called_numbers: Number of unique non-Twilio PSTN called numbers during the report period. + :ivar blocked_calls_by_carrier: Percentage of blocked calls by carrier per country. + :ivar short_duration_calls_percentage: Percentage of completed outbound calls under 10 seconds (PSTN Short call tags); More than 15% is typically low trust measured. + :ivar long_duration_calls_percentage: Percentage of long duration calls ( >= 60 seconds) + :ivar potential_robocalls_percentage: Percentage of completed outbound calls to unassigned or unallocated phone numbers. + :ivar branded_calling: + :ivar voice_integrity: + :ivar stir_shaken: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_calling_numbers: Optional[int] = payload.get( + "unique_calling_numbers" + ) + self.unique_called_numbers: Optional[int] = payload.get( + "unique_called_numbers" + ) + self.blocked_calls_by_carrier: Optional[List[CountyCarrierValue]] = ( + payload.get("blocked_calls_by_carrier") + ) + self.short_duration_calls_percentage: Optional[float] = payload.get( + "short_duration_calls_percentage" + ) + self.long_duration_calls_percentage: Optional[float] = payload.get( + "long_duration_calls_percentage" + ) + self.potential_robocalls_percentage: Optional[float] = payload.get( + "potential_robocalls_percentage" + ) + self.branded_calling: Optional[BrandedCalling] = payload.get( + "branded_calling" + ) + self.voice_integrity: Optional[VoiceIntegrity] = payload.get( + "voice_integrity" + ) + self.stir_shaken: Optional[StirShaken] = payload.get("stir_shaken") + + def to_dict(self): + return { + "unique_calling_numbers": self.unique_calling_numbers, + "unique_called_numbers": self.unique_called_numbers, + "blocked_calls_by_carrier": ( + [ + blocked_calls_by_carrier.to_dict() + for blocked_calls_by_carrier in self.blocked_calls_by_carrier + ] + if self.blocked_calls_by_carrier is not None + else None + ), + "short_duration_calls_percentage": self.short_duration_calls_percentage, + "long_duration_calls_percentage": self.long_duration_calls_percentage, + "potential_robocalls_percentage": self.potential_robocalls_percentage, + "branded_calling": ( + self.branded_calling.to_dict() + if self.branded_calling is not None + else None + ), + "voice_integrity": ( + self.voice_integrity.to_dict() + if self.voice_integrity is not None + else None + ), + "stir_shaken": ( + self.stir_shaken.to_dict() if self.stir_shaken is not None else None + ), + } + + class AccountReportNetworkIssues(object): + """ + :ivar sdk: + :ivar twilio_gateway: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sdk: Optional[AccountReportNetworkIssuesSdk] = payload.get("sdk") + self.twilio_gateway: Optional[AccountReportNetworkIssuesTwilioGateway] = ( + payload.get("twilio_gateway") + ) + + def to_dict(self): + return { + "sdk": self.sdk.to_dict() if self.sdk is not None else None, + "twilio_gateway": ( + self.twilio_gateway.to_dict() + if self.twilio_gateway is not None + else None + ), + } + + class AccountReportNetworkIssuesSdk(object): + """ + :ivar ice_failures_percentage: Percentage of ICE connection failure tag that ICE candidates have failed to find compatible connection. + :ivar high_latency_percentage: Percentage of calls with high latency. + :ivar high_packet_loss_percentage: Percentage of calls with high packet loss. + :ivar high_jitter_percentage: Percentage of calls with high jitter. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.ice_failures_percentage: Optional[float] = payload.get( + "ice_failures_percentage" + ) + self.high_latency_percentage: Optional[float] = payload.get( + "high_latency_percentage" + ) + self.high_packet_loss_percentage: Optional[float] = payload.get( + "high_packet_loss_percentage" + ) + self.high_jitter_percentage: Optional[float] = payload.get( + "high_jitter_percentage" + ) + + def to_dict(self): + return { + "ice_failures_percentage": self.ice_failures_percentage, + "high_latency_percentage": self.high_latency_percentage, + "high_packet_loss_percentage": self.high_packet_loss_percentage, + "high_jitter_percentage": self.high_jitter_percentage, + } + + class AccountReportNetworkIssuesTwilioGateway(object): + """ + :ivar high_latency_percentage: Percentage of calls with high latency. + :ivar high_packet_loss_percentage: Percentage of calls with high packet loss. + :ivar high_jitter_percentage: Percentage of calls with high jitter. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.high_latency_percentage: Optional[float] = payload.get( + "high_latency_percentage" + ) + self.high_packet_loss_percentage: Optional[float] = payload.get( + "high_packet_loss_percentage" + ) + self.high_jitter_percentage: Optional[float] = payload.get( + "high_jitter_percentage" + ) + + def to_dict(self): + return { + "high_latency_percentage": self.high_latency_percentage, + "high_packet_loss_percentage": self.high_packet_loss_percentage, + "high_jitter_percentage": self.high_jitter_percentage, + } + + class BrandedCalling(object): + """ + :ivar total_branded_calls: Total number of Branded bundled calls. + :ivar percent_branded_calls: Percentage of Branded bundled calls over total outbound calls. + :ivar answer_rate: Answer rate for Branded bundled calls. + :ivar human_answer_rate: Rate of Branded bundled calls that were answered by Human. + :ivar engagement_rate: Engagement Rate for Branded bundled calls where its call length is longer than 60 seconds. + :ivar by_use_case: Details of branded calls by use case. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_branded_calls: Optional[int] = payload.get("total_branded_calls") + self.percent_branded_calls: Optional[float] = payload.get( + "percent_branded_calls" + ) + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + self.engagement_rate: Optional[float] = payload.get("engagement_rate") + self.by_use_case: Optional[List[BrandedUseCaseDetail]] = payload.get( + "by_use_case" + ) + + def to_dict(self): + return { + "total_branded_calls": self.total_branded_calls, + "percent_branded_calls": self.percent_branded_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + "engagement_rate": self.engagement_rate, + "by_use_case": ( + [by_use_case.to_dict() for by_use_case in self.by_use_case] + if self.by_use_case is not None + else None + ), + } + + class BrandedUseCaseDetail(object): + """ + :ivar use_case: The name of supported use case for Branded calls. + :ivar enabled_phonenumbers: The number of phone numbers enabled Branded calls. + :ivar total_calls: The number of total outbound calls for the use case. + :ivar answer_rate: Answer rate per each use case for Branded bundled calls. + :ivar human_answer_rate: Rate of Branded bundled calls that were answered by Human per each use case for Branded bundled calls. + :ivar engagement_rate: Engagement Rate for Branded bundled calls where its call length is longer than 60 seconds per each use case for Branded bundled calls. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.use_case: Optional[str] = payload.get("use_case") + self.enabled_phonenumbers: Optional[int] = payload.get( + "enabled_phonenumbers" + ) + self.total_calls: Optional[int] = payload.get("total_calls") + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + self.engagement_rate: Optional[float] = payload.get("engagement_rate") + + def to_dict(self): + return { + "use_case": self.use_case, + "enabled_phonenumbers": self.enabled_phonenumbers, + "total_calls": self.total_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + "engagement_rate": self.engagement_rate, + } + + class CountyCarrierValueCarriers(object): + """ + :ivar carrier: The name of the carrier. + :ivar total_calls: Total number of outbound calls for the carrier in the country. + :ivar blocked_calls: Total number of blocked outbound calls for the carrier in the country. + :ivar blocked_calls_percentage: Percentage of blocked outbound calls for the carrier in the country. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[str] = payload.get("carrier") + self.total_calls: Optional[int] = payload.get("total_calls") + self.blocked_calls: Optional[int] = payload.get("blocked_calls") + self.blocked_calls_percentage: Optional[float] = payload.get( + "blocked_calls_percentage" + ) + + def to_dict(self): + return { + "carrier": self.carrier, + "total_calls": self.total_calls, + "blocked_calls": self.blocked_calls, + "blocked_calls_percentage": self.blocked_calls_percentage, + } + + class InsightsV2CreateAccountReportRequest(object): + """ + :ivar time_range: + :ivar filters: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + ReportList.InsightsV2CreateAccountReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[ReportList.ReportFilter]] = payload.get( + "filters" + ) + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + } + + class InsightsV2CreateAccountReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class StirShaken(object): + """ + :ivar call_count: + :ivar percentage: + :ivar answer_rate: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.call_count: Optional[StirShakenCallCount] = payload.get("call_count") + self.percentage: Optional[StirShakenPercentage] = payload.get("percentage") + self.answer_rate: Optional[StirShakenAnswerRate] = payload.get( + "answer_rate" + ) + + def to_dict(self): + return { + "call_count": ( + self.call_count.to_dict() if self.call_count is not None else None + ), + "percentage": ( + self.percentage.to_dict() if self.percentage is not None else None + ), + "answer_rate": ( + self.answer_rate.to_dict() if self.answer_rate is not None else None + ), + } + + class StirShakenAnswerRate(object): + """ + :ivar stsh_a: Answer rate for Stir Shaken category A. + :ivar stsh_b: Answer rate for Stir Shaken category B. + :ivar stsh_c: Answer rate for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[float] = payload.get("stsh_a") + self.stsh_b: Optional[float] = payload.get("stsh_b") + self.stsh_c: Optional[float] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class StirShakenCallCount(object): + """ + :ivar stsh_a: Total number of calls for Stir Shaken category A. + :ivar stsh_b: Total number of calls for Stir Shaken category B. + :ivar stsh_c: Total number of calls for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[int] = payload.get("stsh_a") + self.stsh_b: Optional[int] = payload.get("stsh_b") + self.stsh_c: Optional[int] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class StirShakenPercentage(object): + """ + :ivar stsh_a: Percentage of calls for Stir Shaken category A. + :ivar stsh_b: Percentage of calls for Stir Shaken category B. + :ivar stsh_c: Percentage of calls for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[float] = payload.get("stsh_a") + self.stsh_b: Optional[float] = payload.get("stsh_b") + self.stsh_c: Optional[float] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class VoiceIntegrity(object): + """ + :ivar enabled_calls: Total number of calls with Voice Integrity enabled. + :ivar enabled_percentage: Percentage of calls with Voice Integrity enabled. + :ivar calls_per_bundle: Number of calls per Voice Integrity enabled Bundle Sid. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.enabled_calls: Optional[int] = payload.get("enabled_calls") + self.enabled_percentage: Optional[float] = payload.get("enabled_percentage") + self.calls_per_bundle: Optional[List[VoiceIntegrityCallsPerBundle]] = ( + payload.get("calls_per_bundle") + ) + + def to_dict(self): + return { + "enabled_calls": self.enabled_calls, + "enabled_percentage": self.enabled_percentage, + "calls_per_bundle": ( + [ + calls_per_bundle.to_dict() + for calls_per_bundle in self.calls_per_bundle + ] + if self.calls_per_bundle is not None + else None + ), + } + + class VoiceIntegrityCallsPerBundle(object): + """ + :ivar bundle_sid: Voice Integrity Approved Profile Sid. + :ivar enabled_phonenumbers: The number of Voice Integrity enabled and registered phone numbers per Bundle Sid. + :ivar total_calls: The number of outbound calls on Voice Integrity enabled and registered number per Bundle Sid. + :ivar answer_rate: Answer rate for calls on Voice Integrity enabled and registered number per Bundle Sid. + :ivar human_answer_rate: Rate for calls on Voice Integrity enabled and registered number per Bundle Sid that were answered by Human per each use case for Branded bundled calls. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.enabled_phonenumbers: Optional[int] = payload.get( + "enabled_phonenumbers" + ) + self.total_calls: Optional[int] = payload.get("total_calls") + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + + def to_dict(self): + return { + "bundle_sid": self.bundle_sid, + "enabled_phonenumbers": self.enabled_phonenumbers, + "total_calls": self.total_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + } + + def __init__(self, version: Version): + """ + Initialize the ReportList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, report_id: str) -> ReportContext: + """ + Constructs a ReportContext + + :param report_id: A unique request id. + """ + return ReportContext(self._version, report_id=report_id) + + def __call__(self, report_id: str) -> ReportContext: + """ + Constructs a ReportContext + + :param report_id: A unique request id. + """ + return ReportContext(self._version, report_id=report_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/insights/v3/__init__.py b/twilio/rest/insights/v3/__init__.py new file mode 100644 index 0000000000..dd519de5fc --- /dev/null +++ b/twilio/rest/insights/v3/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + Insights Domain V3 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.v3.metadata import MetadataList +from twilio.rest.insights.v3.query import QueryList + + +class V3(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V3 version of Insights + + :param domain: The Twilio.insights domain + """ + super().__init__(domain, "v3") + self._metadata: Optional[MetadataList] = None + self._query: Optional[QueryList] = None + + @property + def metadata(self) -> MetadataList: + if self._metadata is None: + self._metadata = MetadataList(self) + return self._metadata + + @property + def query(self) -> QueryList: + if self._query is None: + self._query = QueryList(self) + return self._query + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/insights/v3/metadata.py b/twilio/rest/insights/v3/metadata.py new file mode 100644 index 0000000000..48fe25e158 --- /dev/null +++ b/twilio/rest/insights/v3/metadata.py @@ -0,0 +1,139 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + Insights Domain V3 API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class MetadataInstance(InstanceResource): + """ + :ivar domain: The business domain name for which metadata is being provided + :ivar cubes: List of data cubes available in the domain, each containing measures and dimensions + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.domain: Optional[str] = payload.get("domain") + self.cubes: Optional[List[str]] = payload.get("cubes") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class MetadataList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the MetadataList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/InsightsDomains/Conversations/Metadata" + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MetadataInstance: + """ + Fetch the MetadataInstance + + + :returns: The fetched MetadataInstance + """ + payload, _, _ = self._fetch() + return MetadataInstance(self._version, payload) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MetadataInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MetadataInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> MetadataInstance: + """ + Asynchronously fetch the MetadataInstance + + + :returns: The fetched MetadataInstance + """ + payload, _, _ = await self._fetch_async() + return MetadataInstance(self._version, payload) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously fetch the MetadataInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MetadataInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/insights/v3/query.py b/twilio/rest/insights/v3/query.py new file mode 100644 index 0000000000..e40fa1c744 --- /dev/null +++ b/twilio/rest/insights/v3/query.py @@ -0,0 +1,397 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + Insights Domain V3 API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class QueryInstance(InstanceResource): + """ + :ivar domain: Indicates the business domain the query was executed against + :ivar items: Array of result objects containing the query results. Each object contains properties matching the requested measures and dimensions. + :ivar meta: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.domain: Optional[str] = payload.get("domain") + self.items: Optional[List[Dict[str, object]]] = payload.get("items") + self.meta: Optional[str] = payload.get("meta") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class QueryList(ListResource): + + class InsightsQueryRequest(object): + """ + :ivar domain: The business domain to execute the query against + :ivar query: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.domain: Optional[str] = payload.get("domain") + self.query: Optional[QueryList.QueryDefinition] = payload.get("query") + + def to_dict(self): + return { + "domain": self.domain, + "query": self.query.to_dict() if self.query is not None else None, + } + + class QueryDefinition(object): + """ + :ivar measures: Array of measures to retrieve, representing quantitative values or metrics to be calculated + :ivar dimensions: Array of dimensions to retrieve, representing categorical attributes for grouping and organizing data + :ivar filters: Nested filter conditions. Always use `op` and `expressions`. + :ivar order_by: Specifications for sorting the query results by specific fields in ascending or descending order + """ + + def __init__(self, payload: Dict[str, Any]): + + self.measures: Optional[List[str]] = payload.get("measures") + self.dimensions: Optional[List[str]] = payload.get("dimensions") + self.filters: Optional[List[QueryList.QueryDefinitionFilters]] = ( + payload.get("filters") + ) + self.order_by: Optional[List[QueryList.QueryDefinitionOrderBy]] = ( + payload.get("orderBy") + ) + + def to_dict(self): + return { + "measures": self.measures, + "dimensions": self.dimensions, + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + "orderBy": ( + [order_by.to_dict() for order_by in self.order_by] + if self.order_by is not None + else None + ), + } + + class QueryDefinitionFilters(object): + """ + :ivar op: + :ivar expressions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.op: Optional["QueryInstance.str"] = payload.get("op") + self.expressions: Optional[ + List[QueryList.QueryDefinitionFiltersExpressions] + ] = payload.get("expressions") + + def to_dict(self): + return { + "op": self.op, + "expressions": ( + [expressions.to_dict() for expressions in self.expressions] + if self.expressions is not None + else None + ), + } + + class QueryDefinitionFiltersExpressions(object): + """ + :ivar op: + :ivar field: + :ivar values: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.op: Optional["QueryInstance.str"] = payload.get("op") + self.field: Optional[str] = payload.get("field") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "op": self.op, + "field": self.field, + "values": self.values, + } + + class QueryDefinitionOrderBy(object): + """ + :ivar field: Dimension or measure to order by + :ivar direction: Sort order direction, ascending or descending + """ + + def __init__(self, payload: Dict[str, Any]): + + self.field: Optional[str] = payload.get("field") + self.direction: Optional["QueryInstance.str"] = payload.get("direction") + + def to_dict(self): + return { + "field": self.field, + "direction": self.direction, + } + + def __init__(self, version: Version): + """ + Initialize the QueryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/InsightsDomains/Conversations/Query" + + def _create( + self, + insights_query_request: InsightsQueryRequest, + page_size: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_query_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + params = values.of( + { + "pageSize": page_size, + } + ) + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers, params=params + ) + + def create( + self, + insights_query_request: InsightsQueryRequest, + page_size: Union[int, object] = values.unset, + ) -> QueryInstance: + """ + Create the QueryInstance + + :param insights_query_request: + :param page_size: Number of items per page + + :returns: The created QueryInstance + """ + payload, _, _ = self._create( + insights_query_request=insights_query_request, page_size=page_size + ) + return QueryInstance(self._version, payload) + + def create_with_http_info( + self, + insights_query_request: InsightsQueryRequest, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Create the QueryInstance and return response metadata + + :param insights_query_request: + :param page_size: Number of items per page + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + insights_query_request=insights_query_request, page_size=page_size + ) + instance = QueryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + insights_query_request: InsightsQueryRequest, + page_size: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_query_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + params = values.of( + { + "pageSize": page_size, + } + ) + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers, params=params + ) + + async def create_async( + self, + insights_query_request: InsightsQueryRequest, + page_size: Union[int, object] = values.unset, + ) -> QueryInstance: + """ + Asynchronously create the QueryInstance + + :param insights_query_request: + :param page_size: Number of items per page + + :returns: The created QueryInstance + """ + payload, _, _ = await self._create_async( + insights_query_request=insights_query_request, page_size=page_size + ) + return QueryInstance(self._version, payload) + + async def create_with_http_info_async( + self, + insights_query_request: InsightsQueryRequest, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the QueryInstance and return response metadata + + :param insights_query_request: + :param page_size: Number of items per page + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + insights_query_request=insights_query_request, page_size=page_size + ) + instance = QueryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _fetch(self, page_token: str) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "pageToken": page_token, + } + ) + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers, params=params + ) + + def fetch(self, page_token: str) -> QueryInstance: + """ + Fetch the QueryInstance + + :param page_token: Pagination token + :returns: The fetched QueryInstance + """ + payload, _, _ = self._fetch(page_token=page_token) + return QueryInstance(self._version, payload) + + def fetch_with_http_info(self, page_token: str) -> ApiResponse: + """ + Fetch the QueryInstance and return response metadata + + :param page_token: Pagination token + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(page_token=page_token) + instance = QueryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self, page_token: str) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "pageToken": page_token, + } + ) + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + async def fetch_async(self, page_token: str) -> QueryInstance: + """ + Asynchronously fetch the QueryInstance + + :param page_token: Pagination token + :returns: The fetched QueryInstance + """ + payload, _, _ = await self._fetch_async(page_token=page_token) + return QueryInstance(self._version, payload) + + async def fetch_with_http_info_async(self, page_token: str) -> ApiResponse: + """ + Asynchronously fetch the QueryInstance and return response metadata + + :param page_token: Pagination token + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(page_token=page_token) + instance = QueryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..937e497fe9 --- /dev/null +++ b/twilio/rest/intelligence/IntelligenceBase.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.intelligence.v2 import V2 +from twilio.rest.intelligence.v3 import V3 + + +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 + self._v3: Optional[V3] = None + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Intelligence + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Intelligence + """ + 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/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..899e6e0c6a --- /dev/null +++ b/twilio/rest/intelligence/v2/custom_operator.py @@ -0,0 +1,1245 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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" + GENERAL_AVAILABILITY = "general-availability" + DEPRECATED = "deprecated" + + """ + :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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomOperatorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomOperatorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomOperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomOperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CustomOperatorInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + config=config, + if_match=if_match, + ) + + async def update_with_http_info_async( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CustomOperatorInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the CustomOperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomOperatorInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomOperatorInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomOperatorInstance: + """ + Fetch the CustomOperatorInstance + + + :returns: The fetched CustomOperatorInstance + """ + payload, _, _ = self._fetch() + return CustomOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomOperatorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CustomOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CustomOperatorInstance: + """ + Asynchronous coroutine to fetch the CustomOperatorInstance + + + :returns: The fetched CustomOperatorInstance + """ + payload, _, _ = await self._fetch_async() + return CustomOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomOperatorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CustomOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + friendly_name=friendly_name, config=config, if_match=if_match + ) + return CustomOperatorInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CustomOperatorInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, config=config, if_match=if_match + ) + instance = CustomOperatorInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, config=config, if_match=if_match + ) + return CustomOperatorInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CustomOperatorInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, config=config, if_match=if_match + ) + instance = CustomOperatorInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + friendly_name=friendly_name, operator_type=operator_type, config=config + ) + return CustomOperatorInstance(self._version, payload) + + def create_with_http_info( + self, friendly_name: str, operator_type: str, config: object + ) -> ApiResponse: + """ + Create the CustomOperatorInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, operator_type=operator_type, config=config + ) + instance = CustomOperatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, operator_type: str, config: object + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, operator_type=operator_type, config=config + ) + return CustomOperatorInstance(self._version, payload) + + async def create_with_http_info_async( + self, friendly_name: str, operator_type: str, config: object + ) -> ApiResponse: + """ + Asynchronously create the CustomOperatorInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, operator_type=operator_type, config=config + ) + instance = CustomOperatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CustomOperatorInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams CustomOperatorInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CustomOperatorInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists CustomOperatorInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with CustomOperatorPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CustomOperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with CustomOperatorPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CustomOperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..10c2ea5d5b --- /dev/null +++ b/twilio/rest/intelligence/v2/operator.py @@ -0,0 +1,757 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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" + DEPRECATED = "deprecated" + GENERAL_AVAILABILITY = "general-availability" + 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OperatorInstance: + """ + Fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + payload, _, _ = self._fetch() + return OperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OperatorInstance: + """ + Asynchronous coroutine to fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + payload, _, _ = await self._fetch_async() + return OperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OperatorInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams OperatorInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OperatorInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists OperatorInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with OperatorPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with OperatorPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..d05769e12e --- /dev/null +++ b/twilio/rest/intelligence/v2/operator_attachment.py @@ -0,0 +1,385 @@ +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.api_response import ApiResponse +from twilio.base.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 create_with_http_info(self) -> ApiResponse: + """ + Create the OperatorAttachmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info() + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the OperatorAttachmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OperatorAttachmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OperatorAttachmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self) -> OperatorAttachmentInstance: + """ + Create the OperatorAttachmentInstance + + + :returns: The created OperatorAttachmentInstance + """ + payload, _, _ = self._create() + return OperatorAttachmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the OperatorAttachmentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = OperatorAttachmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self) -> OperatorAttachmentInstance: + """ + Asynchronous coroutine to create the OperatorAttachmentInstance + + + :returns: The created OperatorAttachmentInstance + """ + payload, _, _ = await self._create_async() + return OperatorAttachmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the OperatorAttachmentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = OperatorAttachmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the OperatorAttachmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OperatorAttachmentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OperatorAttachmentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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..0bfbacdcf7 --- /dev/null +++ b/twilio/rest/intelligence/v2/operator_attachments.py @@ -0,0 +1,260 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorAttachmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorAttachmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OperatorAttachmentsInstance: + """ + Fetch the OperatorAttachmentsInstance + + + :returns: The fetched OperatorAttachmentsInstance + """ + payload, _, _ = self._fetch() + return OperatorAttachmentsInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorAttachmentsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperatorAttachmentsInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OperatorAttachmentsInstance: + """ + Asynchronous coroutine to fetch the OperatorAttachmentsInstance + + + :returns: The fetched OperatorAttachmentsInstance + """ + payload, _, _ = await self._fetch_async() + return OperatorAttachmentsInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorAttachmentsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperatorAttachmentsInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..288595ad02 --- /dev/null +++ b/twilio/rest/intelligence/v2/operator_type.py @@ -0,0 +1,736 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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" + JSON = "json" + + 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OperatorTypeInstance: + """ + Fetch the OperatorTypeInstance + + + :returns: The fetched OperatorTypeInstance + """ + payload, _, _ = self._fetch() + return OperatorTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorTypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperatorTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OperatorTypeInstance: + """ + Asynchronous coroutine to fetch the OperatorTypeInstance + + + :returns: The fetched OperatorTypeInstance + """ + payload, _, _ = await self._fetch_async() + return OperatorTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorTypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperatorTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + language_code: Union[str, object] = values.unset, + 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 str language_code: Returns Operator Types 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(language_code=language_code, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + language_code: Union[str, object] = values.unset, + 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 str language_code: Returns Operator Types 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( + language_code=language_code, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OperatorTypeInstance and returns headers from first page + + + :param str language_code: Returns Operator Types 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + language_code=language_code, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OperatorTypeInstance and returns headers from first page + + + :param str language_code: Returns Operator Types 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + language_code=language_code, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + language_code: Union[str, object] = values.unset, + 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 str language_code: Returns Operator Types 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( + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + language_code: Union[str, object] = values.unset, + 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 str language_code: Returns Operator Types 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( + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OperatorTypeInstance and returns headers from first page + + + :param str language_code: Returns Operator Types 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OperatorTypeInstance and returns headers from first page + + + :param str language_code: Returns Operator Types 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + 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, + ) -> OperatorTypePage: + """ + Retrieve a single page of OperatorTypeInstance records from the API. + Request is executed immediately + + :param language_code: Returns Operator Types 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 OperatorTypeInstance + """ + data = values.of( + { + "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 OperatorTypePage(self._version, response) + + async def page_async( + self, + 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, + ) -> OperatorTypePage: + """ + Asynchronously retrieve a single page of OperatorTypeInstance records from the API. + Request is executed immediately + + :param language_code: Returns Operator Types 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 OperatorTypeInstance + """ + data = values.of( + { + "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 OperatorTypePage(self._version, response) + + def page_with_http_info( + self, + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param language_code: Returns Operator Types 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: ApiResponse with OperatorTypePage, status code, and headers + """ + data = values.of( + { + "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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OperatorTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + 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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param language_code: Returns Operator Types 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: ApiResponse with OperatorTypePage, status code, and headers + """ + data = values.of( + { + "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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OperatorTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..8dc5cdac4e --- /dev/null +++ b/twilio/rest/intelligence/v2/prebuilt_operator.py @@ -0,0 +1,780 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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" + GENERAL_AVAILABILITY = "general-availability" + + """ + :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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PrebuiltOperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PrebuiltOperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PrebuiltOperatorInstance: + """ + Fetch the PrebuiltOperatorInstance + + + :returns: The fetched PrebuiltOperatorInstance + """ + payload, _, _ = self._fetch() + return PrebuiltOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PrebuiltOperatorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PrebuiltOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> PrebuiltOperatorInstance: + """ + Asynchronous coroutine to fetch the PrebuiltOperatorInstance + + + :returns: The fetched PrebuiltOperatorInstance + """ + payload, _, _ = await self._fetch_async() + return PrebuiltOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PrebuiltOperatorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PrebuiltOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PrebuiltOperatorInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams PrebuiltOperatorInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PrebuiltOperatorInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists PrebuiltOperatorInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with PrebuiltOperatorPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PrebuiltOperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with PrebuiltOperatorPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PrebuiltOperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..6a16c052fe --- /dev/null +++ b/twilio/rest/intelligence/v2/service.py @@ -0,0 +1,1494 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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. + :ivar encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + """ + + 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.encryption_credential_sid: Optional[str] = payload.get( + "encryption_credential_sid" + ) + + 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + encryption_credential_sid: Union[str, 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: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :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, + encryption_credential_sid=encryption_credential_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, + encryption_credential_sid: Union[str, 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: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :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, + encryption_credential_sid=encryption_credential_sid, + ) + + def update_with_http_info( + 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, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :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: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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, + encryption_credential_sid=encryption_credential_sid, + ) + + async def update_with_http_info_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, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :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: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + encryption_credential_sid=encryption_credential_sid, + ) + + def __repr__(self) -> str: + """ + 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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "EncryptionCredentialSid": encryption_credential_sid, + } + ) + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + encryption_credential_sid: Union[str, 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: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: The updated ServiceInstance + """ + payload, _, _ = self._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, + encryption_credential_sid=encryption_credential_sid, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :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: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + encryption_credential_sid=encryption_credential_sid, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "EncryptionCredentialSid": encryption_credential_sid, + } + ) + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + encryption_credential_sid: Union[str, 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: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: The updated ServiceInstance + """ + payload, _, _ = await self._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, + encryption_credential_sid=encryption_credential_sid, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :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: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + encryption_credential_sid=encryption_credential_sid, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, 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 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, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "EncryptionCredentialSid": encryption_credential_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + encryption_credential_sid: Union[str, 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: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: The created ServiceInstance + """ + payload, _, _ = self._create( + unique_name=unique_name, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + language_code=language_code, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + 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, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :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: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + language_code=language_code, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "EncryptionCredentialSid": encryption_credential_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + encryption_credential_sid: Union[str, 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: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: The created ServiceInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + language_code=language_code, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + return ServiceInstance(self._version, payload) + + async def create_with_http_info_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, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :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: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + language_code=language_code, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..19284fa98d --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/__init__.py @@ -0,0 +1,1364 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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.encrypted_operator_results import ( + EncryptedOperatorResultsList, +) +from twilio.rest.intelligence.v2.transcript.encrypted_sentences import ( + EncryptedSentencesList, +) +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" + NEW = "new" + FAILED = "failed" + CANCELED = "canceled" + ERROR = "error" + + """ + :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 encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + :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.encryption_credential_sid: Optional[str] = payload.get( + "encryption_credential_sid" + ) + 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + @property + def encrypted_operator_results(self) -> EncryptedOperatorResultsList: + """ + Access the encrypted_operator_results + """ + return self._proxy.encrypted_operator_results + + @property + def encrypted_sentences(self) -> EncryptedSentencesList: + """ + Access the encrypted_sentences + """ + return self._proxy.encrypted_sentences + + @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._encrypted_operator_results: Optional[EncryptedOperatorResultsList] = None + self._encrypted_sentences: Optional[EncryptedSentencesList] = None + self._media: Optional[MediaList] = None + self._operator_results: Optional[OperatorResultList] = None + self._sentences: Optional[SentenceList] = None + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the TranscriptInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptInstance: + """ + Fetch the TranscriptInstance + + + :returns: The fetched TranscriptInstance + """ + payload, _, _ = self._fetch() + return TranscriptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TranscriptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TranscriptInstance: + """ + Asynchronous coroutine to fetch the TranscriptInstance + + + :returns: The fetched TranscriptInstance + """ + payload, _, _ = await self._fetch_async() + return TranscriptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TranscriptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def encrypted_operator_results(self) -> EncryptedOperatorResultsList: + """ + Access the encrypted_operator_results + """ + if self._encrypted_operator_results is None: + self._encrypted_operator_results = EncryptedOperatorResultsList( + self._version, + self._solution["sid"], + ) + return self._encrypted_operator_results + + @property + def encrypted_sentences(self) -> EncryptedSentencesList: + """ + Access the encrypted_sentences + """ + if self._encrypted_sentences is None: + self._encrypted_sentences = EncryptedSentencesList( + self._version, + self._solution["sid"], + ) + return self._encrypted_sentences + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + service_sid=service_sid, + channel=channel, + customer_key=customer_key, + media_start_time=media_start_time, + ) + return TranscriptInstance(self._version, payload) + + def create_with_http_info( + self, + service_sid: str, + channel: object, + customer_key: Union[str, object] = values.unset, + media_start_time: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Create the TranscriptInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + service_sid=service_sid, + channel=channel, + customer_key=customer_key, + media_start_time=media_start_time, + ) + instance = TranscriptInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + service_sid=service_sid, + channel=channel, + customer_key=customer_key, + media_start_time=media_start_time, + ) + return TranscriptInstance(self._version, payload) + + async def create_with_http_info_async( + self, + service_sid: str, + channel: object, + customer_key: Union[str, object] = values.unset, + media_start_time: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TranscriptInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + service_sid=service_sid, + channel=channel, + customer_key=customer_key, + media_start_time=media_start_time, + ) + instance = TranscriptInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams TranscriptInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams TranscriptInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists TranscriptInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists TranscriptInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with TranscriptPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TranscriptPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with TranscriptPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TranscriptPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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/encrypted_operator_results.py b/twilio/rest/intelligence/v2/transcript/encrypted_operator_results.py new file mode 100644 index 0000000000..4262a2ce09 --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/encrypted_operator_results.py @@ -0,0 +1,313 @@ +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 +from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.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 EncryptedOperatorResultsInstance(InstanceResource): + """ + :ivar locations: The locations of the encrypted operator results. + :ivar transcript_sid: + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], transcript_sid: str): + super().__init__(version) + + self.locations: Optional[List[str]] = payload.get("locations") + self.transcript_sid: Optional[str] = payload.get("transcript_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "transcript_sid": transcript_sid, + } + + self._context: Optional[EncryptedOperatorResultsContext] = None + + @property + def _proxy(self) -> "EncryptedOperatorResultsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EncryptedOperatorResultsContext for this EncryptedOperatorResultsInstance + """ + if self._context is None: + self._context = EncryptedOperatorResultsContext( + self._version, + transcript_sid=self._solution["transcript_sid"], + ) + return self._context + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> "EncryptedOperatorResultsInstance": + """ + Fetch the EncryptedOperatorResultsInstance + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: The fetched EncryptedOperatorResultsInstance + """ + return self._proxy.fetch( + redacted=redacted, + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> "EncryptedOperatorResultsInstance": + """ + Asynchronous coroutine to fetch the EncryptedOperatorResultsInstance + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: The fetched EncryptedOperatorResultsInstance + """ + return await self._proxy.fetch_async( + redacted=redacted, + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the EncryptedOperatorResultsInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + redacted=redacted, + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EncryptedOperatorResultsInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 EncryptedOperatorResultsContext(InstanceContext): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the EncryptedOperatorResultsContext + + :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}/OperatorResults/Encrypted".format( + **self._solution + ) + + def _fetch(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> EncryptedOperatorResultsInstance: + """ + Fetch the EncryptedOperatorResultsInstance + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: The fetched EncryptedOperatorResultsInstance + """ + payload, _, _ = self._fetch(redacted=redacted) + return EncryptedOperatorResultsInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the EncryptedOperatorResultsInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(redacted=redacted) + instance = EncryptedOperatorResultsInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> EncryptedOperatorResultsInstance: + """ + Asynchronous coroutine to fetch the EncryptedOperatorResultsInstance + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: The fetched EncryptedOperatorResultsInstance + """ + payload, _, _ = await self._fetch_async(redacted=redacted) + return EncryptedOperatorResultsInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EncryptedOperatorResultsInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(redacted=redacted) + instance = EncryptedOperatorResultsInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 EncryptedOperatorResultsList(ListResource): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the EncryptedOperatorResultsList + + :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, + } + + def get(self) -> EncryptedOperatorResultsContext: + """ + Constructs a EncryptedOperatorResultsContext + + """ + return EncryptedOperatorResultsContext( + self._version, transcript_sid=self._solution["transcript_sid"] + ) + + def __call__(self) -> EncryptedOperatorResultsContext: + """ + Constructs a EncryptedOperatorResultsContext + + """ + return EncryptedOperatorResultsContext( + self._version, transcript_sid=self._solution["transcript_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v2/transcript/encrypted_sentences.py b/twilio/rest/intelligence/v2/transcript/encrypted_sentences.py new file mode 100644 index 0000000000..ed2406926e --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/encrypted_sentences.py @@ -0,0 +1,309 @@ +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.api_response import ApiResponse +from twilio.base.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 EncryptedSentencesInstance(InstanceResource): + """ + :ivar location: The location of the encrypted sentences. + :ivar transcript_sid: + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], transcript_sid: str): + super().__init__(version) + + self.location: Optional[str] = payload.get("location") + self.transcript_sid: Optional[str] = payload.get("transcript_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "transcript_sid": transcript_sid, + } + + self._context: Optional[EncryptedSentencesContext] = None + + @property + def _proxy(self) -> "EncryptedSentencesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EncryptedSentencesContext for this EncryptedSentencesInstance + """ + if self._context is None: + self._context = EncryptedSentencesContext( + self._version, + transcript_sid=self._solution["transcript_sid"], + ) + return self._context + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> "EncryptedSentencesInstance": + """ + Fetch the EncryptedSentencesInstance + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: The fetched EncryptedSentencesInstance + """ + return self._proxy.fetch( + redacted=redacted, + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> "EncryptedSentencesInstance": + """ + Asynchronous coroutine to fetch the EncryptedSentencesInstance + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: The fetched EncryptedSentencesInstance + """ + return await self._proxy.fetch_async( + redacted=redacted, + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the EncryptedSentencesInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + redacted=redacted, + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EncryptedSentencesInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 EncryptedSentencesContext(InstanceContext): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the EncryptedSentencesContext + + :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/Encrypted".format( + **self._solution + ) + + def _fetch(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> EncryptedSentencesInstance: + """ + Fetch the EncryptedSentencesInstance + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: The fetched EncryptedSentencesInstance + """ + payload, _, _ = self._fetch(redacted=redacted) + return EncryptedSentencesInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the EncryptedSentencesInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(redacted=redacted) + instance = EncryptedSentencesInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> EncryptedSentencesInstance: + """ + Asynchronous coroutine to fetch the EncryptedSentencesInstance + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: The fetched EncryptedSentencesInstance + """ + payload, _, _ = await self._fetch_async(redacted=redacted) + return EncryptedSentencesInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EncryptedSentencesInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(redacted=redacted) + instance = EncryptedSentencesInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 EncryptedSentencesList(ListResource): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the EncryptedSentencesList + + :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, + } + + def get(self) -> EncryptedSentencesContext: + """ + Constructs a EncryptedSentencesContext + + """ + return EncryptedSentencesContext( + self._version, transcript_sid=self._solution["transcript_sid"] + ) + + def __call__(self) -> EncryptedSentencesContext: + """ + Constructs a EncryptedSentencesContext + + """ + return EncryptedSentencesContext( + self._version, transcript_sid=self._solution["transcript_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..a4d08a488d --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/media.py @@ -0,0 +1,303 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the MediaInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + redacted=redacted, + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MediaInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = self._fetch(redacted=redacted) + return MediaInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the MediaInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(redacted=redacted) + instance = MediaInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(redacted=redacted) + return MediaInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MediaInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(redacted=redacted) + instance = MediaInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..01af814a79 --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/operator_result.py @@ -0,0 +1,806 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the OperatorResultInstance with HTTP info + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + redacted=redacted, + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorResultInstance with HTTP info + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = self._fetch(redacted=redacted) + return OperatorResultInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the OperatorResultInstance and return response metadata + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(redacted=redacted) + instance = OperatorResultInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(redacted=redacted) + return OperatorResultInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorResultInstance and return response metadata + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(redacted=redacted) + instance = OperatorResultInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OperatorResultInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + redacted=redacted, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OperatorResultInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + redacted=redacted, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OperatorResultInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + redacted=redacted, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OperatorResultInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + redacted=redacted, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with OperatorResultPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OperatorResultPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with OperatorResultPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OperatorResultPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..ee11548693 --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/sentence.py @@ -0,0 +1,556 @@ +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.api_response import ApiResponse + +from twilio.base.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[str] = payload.get("start_time") + self.end_time: Optional[str] = payload.get("end_time") + self.transcript: Optional[str] = payload.get("transcript") + self.sid: Optional[str] = payload.get("sid") + self.confidence: Optional[str] = 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 stream_with_http_info( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SentenceInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + redacted=redacted, + word_timestamps=word_timestamps, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SentenceInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + redacted=redacted, + word_timestamps=word_timestamps, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SentenceInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + redacted=redacted, + word_timestamps=word_timestamps, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SentenceInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + redacted=redacted, + word_timestamps=word_timestamps, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with SentencePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SentencePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with SentencePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SentencePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v3/__init__.py b/twilio/rest/intelligence/v3/__init__.py new file mode 100644 index 0000000000..2e3f84bdf5 --- /dev/null +++ b/twilio/rest/intelligence/v3/__init__.py @@ -0,0 +1,82 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Conversational Intelligence API + The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + + NOTE: This 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.v3.configuration import ConfigurationList +from twilio.rest.intelligence.v3.conversation import ConversationList +from twilio.rest.intelligence.v3.operator import OperatorList +from twilio.rest.intelligence.v3.operator_result import OperatorResultList +from twilio.rest.intelligence.v3.version import VersionList + + +class V3(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V3 version of Intelligence + + :param domain: The Twilio.intelligence domain + """ + super().__init__(domain, "v3") + self._configurations: Optional[ConfigurationList] = None + self._conversations: Optional[ConversationList] = None + self._operators: Optional[OperatorList] = None + self._operator_results: Optional[OperatorResultList] = None + + @property + def configurations(self) -> ConfigurationList: + if self._configurations is None: + self._configurations = ConfigurationList(self) + return self._configurations + + @property + def conversations(self) -> ConversationList: + if self._conversations is None: + self._conversations = ConversationList(self) + return self._conversations + + @property + def operators(self) -> OperatorList: + if self._operators is None: + self._operators = OperatorList(self) + return self._operators + + @property + def operator_results(self) -> OperatorResultList: + if self._operator_results is None: + self._operator_results = OperatorResultList(self) + return self._operator_results + + def versions(self, id: str, version_id: str = None): + """ + Access the VersionList resource + + :param id: The unique identifier (TTID) of the Language Operator. + + :param version_id: Optional instance ID to directly access VersionContext + :returns: VersionList instance if version_id is None, otherwise VersionContext + """ + list_instance = VersionList(self, id) + if version_id is not None: + return list_instance(version_id) + return list_instance + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v3/configuration.py b/twilio/rest/intelligence/v3/configuration.py new file mode 100644 index 0000000000..d67f2057b5 --- /dev/null +++ b/twilio/rest/intelligence/v3/configuration.py @@ -0,0 +1,1333 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Conversational Intelligence API + The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ConfigurationInstance(InstanceResource): + """ + :ivar code: Twilio-specific error code + :ivar message: A human readable error message + :ivar http_status_code: HTTP response status code + :ivar user_error: Whether the error is a user error (true) or a system error (false) + :ivar params: A map of parameters related to the error, for example, a `params.twilioErrorCodeUrl` might hold a URL or link to additional information + :ivar account_id: The ID of the Account that created the Intelligence Configuration. + :ivar id: The unique identifier for the Intelligence Configuration. Assigned by Twilio (TTID). + :ivar display_name: The display name of the Intelligence Configuration describing its purpose. + :ivar description: The description of the Intelligence Configuration further explaining its purpose. + :ivar version: The numeric version of the Intelligence Configuration. Automatically incremented with each update on the resource, used to ensure integrity when updating the Configuration. + :ivar rules: List of Intelligence Configuration Rules that govern when and how Language Operators run. Each Rule represents a bundle of Operators, Triggers, Context, and Actions to be executed by the Intelligence Configuration on a Conversation. A maximum of five (5) Rules are allowed per Intelligence Configuration. + :ivar date_created: Timestamp of when the Intelligence Configuration was created. + :ivar date_updated: Timestamp of when the Intelligence Configuration was last updated. + """ + + def __init__( + self, version: Version, payload: ResponseResource, id: Optional[str] = None + ): + super().__init__(version) + + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.http_status_code: Optional[int] = payload.get("httpStatusCode") + self.user_error: Optional[bool] = payload.get("userError") + self.params: Optional[Dict[str, str]] = payload.get("params") + self.account_id: Optional[str] = payload.get("accountId") + self.id: Optional[str] = payload.get("id") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.rules: Optional[List[str]] = payload.get("rules") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateCreated") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateUpdated") + ) + + # Only set _solution if path params are provided (not None) + if id is not None: + self._solution = { + "id": id, + } + + 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, + id=self._solution["id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, update_configuration_request: UpdateConfigurationRequest + ) -> "ConfigurationInstance": + """ + Update the ConfigurationInstance + + :param update_configuration_request: + + :returns: The updated ConfigurationInstance + """ + return self._proxy.update( + update_configuration_request=update_configuration_request, + ) + + async def update_async( + self, update_configuration_request: UpdateConfigurationRequest + ) -> "ConfigurationInstance": + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param update_configuration_request: + + :returns: The updated ConfigurationInstance + """ + return await self._proxy.update_async( + update_configuration_request=update_configuration_request, + ) + + def update_with_http_info( + self, update_configuration_request: UpdateConfigurationRequest + ) -> ApiResponse: + """ + Update the ConfigurationInstance with HTTP info + + :param update_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + update_configuration_request=update_configuration_request, + ) + + async def update_with_http_info_async( + self, update_configuration_request: UpdateConfigurationRequest + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance with HTTP info + + :param update_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + update_configuration_request=update_configuration_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 ConfigurationContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the ConfigurationContext + + :param version: Version that contains the resource + :param id: The unique identifier of the Intelligence Configuration. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/ControlPlane/Configurations/{id}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConfigurationInstance: + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = self._fetch() + return ConfigurationInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConfigurationInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = await self._fetch_async() + return ConfigurationInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConfigurationInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, update_configuration_request: UpdateConfigurationRequest + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_configuration_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, update_configuration_request: UpdateConfigurationRequest + ) -> ConfigurationInstance: + """ + Update the ConfigurationInstance + + :param update_configuration_request: + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = self._update( + update_configuration_request=update_configuration_request + ) + return ConfigurationInstance(self._version, payload, id=self._solution["id"]) + + def update_with_http_info( + self, update_configuration_request: UpdateConfigurationRequest + ) -> ApiResponse: + """ + Update the ConfigurationInstance and return response metadata + + :param update_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + update_configuration_request=update_configuration_request + ) + instance = ConfigurationInstance( + self._version, payload, id=self._solution["id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, update_configuration_request: UpdateConfigurationRequest + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_configuration_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, update_configuration_request: UpdateConfigurationRequest + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param update_configuration_request: + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = await self._update_async( + update_configuration_request=update_configuration_request + ) + return ConfigurationInstance(self._version, payload, id=self._solution["id"]) + + async def update_with_http_info_async( + self, update_configuration_request: UpdateConfigurationRequest + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance and return response metadata + + :param update_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + update_configuration_request=update_configuration_request + ) + instance = ConfigurationInstance( + self._version, payload, id=self._solution["id"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 ConfigurationPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ConfigurationInstance: + """ + Build an instance of ConfigurationInstance + + :param payload: Payload response from the API + """ + + return ConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConfigurationList(ListResource): + + class Action(object): + """ + :ivar type: The type of Action to be performed after the Rule is triggered. Supported Actions are: - `WEBHOOK`: A webhook Action sends an HTTP request to a specified URL with Rule execution results. + :ivar method: The HTTP method to be used when performing the Action. Must be set to `POST`. + :ivar url: The URL endpoint where the Action will send the HTTP request containing the Rule execution results. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ConfigurationInstance.str"] = payload.get("type") + self.method: Optional["ConfigurationInstance.str"] = payload.get("method") + self.url: Optional[str] = payload.get("url") + + def to_dict(self): + return { + "type": self.type, + "method": self.method, + "url": self.url, + } + + class Context(object): + """ + :ivar memory: + :ivar knowledge: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.memory: Optional[ConfigurationList.ContextMemory] = payload.get( + "memory" + ) + self.knowledge: Optional[ConfigurationList.ContextKnowledge] = payload.get( + "knowledge" + ) + + def to_dict(self): + return { + "memory": self.memory.to_dict() if self.memory is not None else None, + "knowledge": ( + self.knowledge.to_dict() if self.knowledge is not None else None + ), + } + + class ContextKnowledge(object): + """ + :ivar bases: Specifies the Knowledge Base(s) and corresponding Source(s) to pass to Language Operators in this Rule as context. Only applied to Language Operators that have Knowledge as a context source enabled. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.bases: Optional[List[str]] = payload.get("bases") + + def to_dict(self): + return { + "bases": self.bases, + } + + class ContextMemory(object): + """ + :ivar enabled: When set to `true`, allows this Intelligence Configuration Rule to pass the Profile into attached Language Operators. The profile is only passed to Language Operators that have Memory as a context source enabled. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.enabled: Optional[bool] = payload.get("enabled") + + def to_dict(self): + return { + "enabled": self.enabled, + } + + class CreateConfigurationRequest(object): + """ + :ivar display_name: The display name of the Intelligence Configuration describing its purpose. + :ivar description: The description of the Intelligence Configuration further explaining its purpose. + :ivar rules: List of Intelligence Configuration Rules that govern when and how Language Operators run. Each Rule represents a bundle of Operators, Triggers, Context, and Actions to be executed by the Intelligence Configuration on a Conversation. A maximum of five (5) Rules are allowed per Intelligence Configuration. To create an Intelligence Configuration without any Rules configured yet, pass an empty array (`\"rules\": []`). The Configuration will not execute any Language Operators until at least one Rule has been added. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.rules: Optional[List[ConfigurationList.RuleCreationRequestPayload]] = ( + payload.get("rules") + ) + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "rules": ( + [rules.to_dict() for rules in self.rules] + if self.rules is not None + else None + ), + } + + class Operator(object): + """ + :ivar id: The unique identifier for the Language Operator to be executed by the Rule. Assigned by Twilio (TTID). + :ivar version: The specific version of the Language Operator to execute. When provided, the Rule will use this exact version of the Operator. When omitted, the latest active version of the Operator is used at execution time. + :ivar parameters: Key-value mapping for parameters defined as part of the Operator schema. The key and value passed by the Rule must match the name and data type of the parameter defined in the Operator, respectively. These parameters will customize the behavior of the Operator when executed by the Rule via runtime substitution into the prompt. Note: For parameters of type `knowledge_base_and_source_ids`, the value must be passed in the following format: `knowledge_base_id:knowledge_source_id`. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.version: Optional[int] = payload.get("version") + self.parameters: Optional[Dict[str, object]] = payload.get("parameters") + + def to_dict(self): + return { + "id": self.id, + "version": self.version, + "parameters": self.parameters, + } + + class RuleCreationRequestPayload(object): + """ + :ivar operators: List of Operators to be executed by the Rule. Minimum of one (1) and maximum of five (5) Operators allowed per Rule. + :ivar triggers: List of Triggers that determine when to activate the Rule. Maximum of one (1) Trigger allowed per Rule. + :ivar actions: List of Actions to be performed after the Rule is triggered. Maximum of two (2) Actions allowed per Rule. + :ivar context: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.operators: Optional[List[ConfigurationList.Operator]] = payload.get( + "operators" + ) + self.triggers: Optional[List[ConfigurationList.Trigger]] = payload.get( + "triggers" + ) + self.actions: Optional[List[ConfigurationList.Action]] = payload.get( + "actions" + ) + self.context: Optional[ConfigurationList.Context] = payload.get("context") + + def to_dict(self): + return { + "operators": ( + [operators.to_dict() for operators in self.operators] + if self.operators is not None + else None + ), + "triggers": ( + [triggers.to_dict() for triggers in self.triggers] + if self.triggers is not None + else None + ), + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + "context": self.context.to_dict() if self.context is not None else None, + } + + class RuleUpdateRequestPayload(object): + """ + :ivar id: Optional field used when updating an existing Rule within an Intelligence Configuration. When provided, the Rule with this `id` is updated; when omitted, a new Rule is created. + :ivar operators: List of Operators to be executed by the Rule. Minimum of one (1) and maximum of five (5) Operators allowed per Rule. + :ivar triggers: List of Triggers that determine when to activate the Rule. Maximum of one (1) Trigger allowed per Rule. + :ivar actions: List of Actions to be performed after the Rule is triggered. Maximum of two (2) Actions allowed per Rule. + :ivar context: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.operators: Optional[List[ConfigurationList.Operator]] = payload.get( + "operators" + ) + self.triggers: Optional[List[ConfigurationList.Trigger]] = payload.get( + "triggers" + ) + self.actions: Optional[List[ConfigurationList.Action]] = payload.get( + "actions" + ) + self.context: Optional[ConfigurationList.Context] = payload.get("context") + + def to_dict(self): + return { + "id": self.id, + "operators": ( + [operators.to_dict() for operators in self.operators] + if self.operators is not None + else None + ), + "triggers": ( + [triggers.to_dict() for triggers in self.triggers] + if self.triggers is not None + else None + ), + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + "context": self.context.to_dict() if self.context is not None else None, + } + + class Trigger(object): + """ + :ivar on: The conversational lifecycle event that will activate execution of the Rule. Available values are: - `COMMUNICATION`: Trigger the Rule on each communication within the Conversation. - `CONVERSATION_END`: Trigger the Rule when the Conversation moves to the `closed` state - `CONVERSATION_INACTIVE`: Trigger the Rule when the Conversation moves to `inactive` state + :ivar parameters: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.on: Optional["ConfigurationInstance.str"] = payload.get("on") + self.parameters: Optional[ConfigurationList.TriggerParameters] = ( + payload.get("parameters") + ) + + def to_dict(self): + return { + "on": self.on, + "parameters": ( + self.parameters.to_dict() if self.parameters is not None else None + ), + } + + class TriggerParameters(object): + """ + :ivar count: When `on` is set to `COMMUNICATION`, this value controls how often the Rule should run. A value of `1` executes the Rule for every communication event. Higher values delay execution until the specified number of communications have occurred since the last execution. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.count: Optional[int] = payload.get("count") + + def to_dict(self): + return { + "count": self.count, + } + + class UpdateConfigurationRequest(object): + """ + :ivar display_name: The display name of the Intelligence Configuration describing its purpose. + :ivar description: The description of the Intelligence Configuration further explaining its purpose. + :ivar rules: List of Intelligence Configuration Rules that govern when and how Language Operators run. Each Rule represents a bundle of Operators, Triggers, Context, and Actions to be executed by the Intelligence Configuration on a Conversation. A maximum of five (5) Rules are allowed per Intelligence Configuration. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.rules: Optional[List[ConfigurationList.RuleUpdateRequestPayload]] = ( + payload.get("rules") + ) + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "rules": ( + [rules.to_dict() for rules in self.rules] + if self.rules is not None + else None + ), + } + + def __init__(self, version: Version): + """ + Initialize the ConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ControlPlane/Configurations" + + def _create( + self, create_configuration_request: CreateConfigurationRequest + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_configuration_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_configuration_request: CreateConfigurationRequest + ) -> ConfigurationInstance: + """ + Create the ConfigurationInstance + + :param create_configuration_request: + + :returns: The created ConfigurationInstance + """ + payload, _, _ = self._create( + create_configuration_request=create_configuration_request + ) + return ConfigurationInstance(self._version, payload) + + def create_with_http_info( + self, create_configuration_request: CreateConfigurationRequest + ) -> ApiResponse: + """ + Create the ConfigurationInstance and return response metadata + + :param create_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_configuration_request=create_configuration_request + ) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_configuration_request: CreateConfigurationRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_configuration_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_configuration_request: CreateConfigurationRequest + ) -> ConfigurationInstance: + """ + Asynchronously create the ConfigurationInstance + + :param create_configuration_request: + + :returns: The created ConfigurationInstance + """ + payload, _, _ = await self._create_async( + create_configuration_request=create_configuration_request + ) + return ConfigurationInstance(self._version, payload) + + async def create_with_http_info_async( + self, create_configuration_request: CreateConfigurationRequest + ) -> ApiResponse: + """ + Asynchronously create the ConfigurationInstance and return response metadata + + :param create_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_configuration_request=create_configuration_request + ) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConfigurationInstance]: + """ + Streams ConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_token=page_token, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConfigurationInstance]: + """ + Asynchronously streams ConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConfigurationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConfigurationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConfigurationInstance]: + """ + Lists ConfigurationInstance 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: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConfigurationInstance]: + """ + Asynchronously lists ConfigurationInstance 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: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConfigurationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConfigurationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ConfigurationPage: + """ + Retrieve a single page of ConfigurationInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of ConfigurationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConfigurationPage(self._version, response, uri=self._uri, params=data) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ConfigurationPage: + """ + Asynchronously retrieve a single page of ConfigurationInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of ConfigurationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConfigurationPage(self._version, response, uri=self._uri, params=data) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConfigurationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConfigurationPage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConfigurationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ConfigurationPage: + """ + Retrieve a specific page of ConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConfigurationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConfigurationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConfigurationPage: + """ + Asynchronously retrieve a specific page of ConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConfigurationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConfigurationPage(self._version, response) + + def get(self, id: str) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + :param id: The unique identifier of the Intelligence Configuration. + """ + return ConfigurationContext(self._version, id=id) + + def __call__(self, id: str) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + :param id: The unique identifier of the Intelligence Configuration. + """ + return ConfigurationContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v3/conversation.py b/twilio/rest/intelligence/v3/conversation.py new file mode 100644 index 0000000000..0d99163014 --- /dev/null +++ b/twilio/rest/intelligence/v3/conversation.py @@ -0,0 +1,1016 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Conversational Intelligence API + The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ConversationInstance(InstanceResource): + + class Channel(object): + VOICE = "VOICE" + SMS = "SMS" + RCS = "RCS" + EMAIL = "EMAIL" + WHATSAPP = "WHATSAPP" + CHAT = "CHAT" + API = "API" + SYSTEM = "SYSTEM" + + class ConversationStatus(object): + ACTIVE = "ACTIVE" + INACTIVE = "INACTIVE" + CLOSED = "CLOSED" + + """ + :ivar id: The `id` of the Conversation attached to the Operator Result. + :ivar account_id: The ID of the account that owns the Conversation. + :ivar name: Display name of the Conversation. + :ivar status: + :ivar created_at: Timestamp for when the Conversation was created. + :ivar updated_at: Timestamp for when the Conversation was last updated. + :ivar intelligence_configuration_ids: The Intelligence Configuration(s) associated with the Conversation. + :ivar conversation_configuration_id: The `id` of the Configuration for a Conversation. + :ivar channels: The communication channel(s) included in the Conversation. + :ivar channel_ids: The underlying channel resource `id`s associated with this Conversation, such as a Call ID or Message ID. + :ivar participants: Metadata for Participants of the Conversation. + :ivar communications: Metadata for the Communications that make up the Conversation. + :ivar operator_result_ids: List of Operator Result IDs generated from this Conversation. + """ + + def __init__( + self, version: Version, payload: ResponseResource, id: Optional[str] = None + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.account_id: Optional[str] = payload.get("accountId") + self.name: Optional[str] = payload.get("name") + self.status: Optional["ConversationInstance.str"] = payload.get("status") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.intelligence_configuration_ids: Optional[List[str]] = payload.get( + "intelligenceConfigurationIds" + ) + self.conversation_configuration_id: Optional[str] = payload.get( + "conversationConfigurationId" + ) + self.channels: Optional[List[Enumstr]] = payload.get("channels") + self.channel_ids: Optional[List[str]] = payload.get("channelIds") + self.participants: Optional[List[str]] = payload.get("participants") + self.communications: Optional[List[str]] = payload.get("communications") + self.operator_result_ids: Optional[List[str]] = payload.get("operatorResultIds") + + # Only set _solution if path params are provided (not None) + if id is not None: + self._solution = { + "id": id, + } + + 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, + id=self._solution["id"], + ) + return self._context + + 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 ConversationContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the ConversationContext + + :param version: Version that contains the resource + :param id: The unique identifier of the conversation. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Conversations/{id}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConversationInstance: + """ + Fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + payload, _, _ = self._fetch() + return ConversationInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConversationInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConversationInstance: + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + payload, _, _ = await self._fetch_async() + return ConversationInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConversationInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 ConversationPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ConversationInstance: + """ + Build an instance of ConversationInstance + + :param payload: Payload response from the API + """ + + return ConversationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConversationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConversationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Conversations" + + def stream( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], 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 page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], 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 page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConversationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConversationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], 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 page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` 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( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], 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 page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` 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( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConversationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConversationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + ) -> ConversationPage: + """ + Retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :param created_at_before: Filter by Conversations created before this timestamp. + :param created_at_after: Filter by Conversations created after this timestamp. + :param status: Filter by Conversation status. + :param channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :returns: Page of ConversationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "createdAtBefore": serialize.iso8601_datetime(created_at_before), + "createdAtAfter": serialize.iso8601_datetime(created_at_after), + "status": status, + "channelId": channel_id, + "channels": serialize.map(channels, lambda e: e), + "conversationConfigurationId": conversation_configuration_id, + "intelligenceConfigurationIds": serialize.map( + intelligence_configuration_ids, lambda e: e + ), + "operatorIds": serialize.map(operator_ids, lambda e: e), + } + ) + + headers = values.of({"Content-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, uri=self._uri, params=data) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + ) -> ConversationPage: + """ + Asynchronously retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :param created_at_before: Filter by Conversations created before this timestamp. + :param created_at_after: Filter by Conversations created after this timestamp. + :param status: Filter by Conversation status. + :param channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :returns: Page of ConversationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "createdAtBefore": serialize.iso8601_datetime(created_at_before), + "createdAtAfter": serialize.iso8601_datetime(created_at_after), + "status": status, + "channelId": channel_id, + "channels": serialize.map(channels, lambda e: e), + "conversationConfigurationId": conversation_configuration_id, + "intelligenceConfigurationIds": serialize.map( + intelligence_configuration_ids, lambda e: e + ), + "operatorIds": serialize.map(operator_ids, lambda e: e), + } + ) + + headers = values.of({"Content-Type": "application/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, uri=self._uri, params=data) + + def page_with_http_info( + self, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param created_at_before: Filter by Conversations created before this timestamp. + :param created_at_after: Filter by Conversations created after this timestamp. + :param status: Filter by Conversation status. + :param channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` 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: ApiResponse with ConversationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "createdAtBefore": serialize.iso8601_datetime(created_at_before), + "createdAtAfter": serialize.iso8601_datetime(created_at_after), + "status": status, + "channelId": channel_id, + "channels": serialize.map(channels, lambda e: e), + "conversationConfigurationId": conversation_configuration_id, + "intelligenceConfigurationIds": serialize.map( + intelligence_configuration_ids, lambda e: e + ), + "operatorIds": serialize.map(operator_ids, 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConversationPage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: 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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param created_at_before: Filter by Conversations created before this timestamp. + :param created_at_after: Filter by Conversations created after this timestamp. + :param status: Filter by Conversation status. + :param channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` 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: ApiResponse with ConversationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "createdAtBefore": serialize.iso8601_datetime(created_at_before), + "createdAtAfter": serialize.iso8601_datetime(created_at_after), + "status": status, + "channelId": channel_id, + "channels": serialize.map(channels, lambda e: e), + "conversationConfigurationId": conversation_configuration_id, + "intelligenceConfigurationIds": serialize.map( + intelligence_configuration_ids, lambda e: e + ), + "operatorIds": serialize.map(operator_ids, 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConversationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ConversationPage: + """ + Retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConversationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConversationPage: + """ + Asynchronously retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConversationPage(self._version, response) + + def get(self, id: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param id: The unique identifier of the conversation. + """ + return ConversationContext(self._version, id=id) + + def __call__(self, id: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param id: The unique identifier of the conversation. + """ + return ConversationContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v3/operator.py b/twilio/rest/intelligence/v3/operator.py new file mode 100644 index 0000000000..6306102919 --- /dev/null +++ b/twilio/rest/intelligence/v3/operator.py @@ -0,0 +1,1242 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Conversational Intelligence API + The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class OperatorInstance(InstanceResource): + + class OperatorAuthor(object): + SELF = "SELF" + TWILIO = "TWILIO" + + class OperatorOutputFormat(object): + TEXT = "TEXT" + JSON = "JSON" + CLASSIFICATION = "CLASSIFICATION" + + """ + :ivar code: Twilio-specific error code + :ivar message: A human readable error message + :ivar http_status_code: HTTP response status code + :ivar user_error: Whether the error is a user error (true) or a system error (false) + :ivar params: A map of parameters related to the error, for example, a `params.twilioErrorCodeUrl` might hold a URL or link to additional information + :ivar id: The unique identifier for the Language Operator. Assigned by Twilio (TTID). + :ivar display_name: Display name of the Language Operator describing its purpose. + :ivar description: Description of the Language Operator further explaining its purpose. + :ivar version: Numeric Operator version. Automatically incremented with each update on the resource, used to ensure integrity when updating the Operator. + :ivar author: + :ivar prompt: The natural language instructions used by the operator to analyze the conversation. Within the prompt, users can reference parameters using the `{{parameters.[param_name]}}` syntax. Parameter values are provided to the Operator by the Intelligence Configuration Rule at runtime. **Note**: Prompts will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their prompts omitted from the API. + :ivar output_format: + :ivar output_schema: Required for `JSON` output only. this will be set to a JSON Schema object describing the properties & data types of the response. Please see https://platform.openai.com/docs/guides/structured-outputs#supported-schemas Will include the following keywords: - `type` : Must be set to `object` - `properties`: An object containing the property names and their data types you would like the LLM to return Additional details on JSON output formatting: - The root level `type` of a JSON schema must be set to `object` - The following property data types are supported : `string`, `number`, `boolean`, `integer`, `object`, `array`, `anyOf` - Definitions with `$defs` / `$ref` are supported - Max 100 object properties and 10 levels of nesting are supported - Max 1000 enum values across all enum properties are supported - Notable JSON Schema keywords not supported include: - For `strings`: `minLength`, `maxLength` - For `objects`: `patternProperties`, `unevaluatedProperties`, `propertyNames`, `minProperties`, `maxProperties` - For `arrays`: `unevaluatedItems`, `contains`, `minContains`, `maxContains`, `uniqueItems` - Structured Operator Results will be returned in the same order as the ordering of keys in the schema - In the event an Operator execution request is refused for safety reasons the Operator Result API response will include a new field called `refusal` to indicate that the LLM refused to fulfill the request - Twilio will automatically set `additionalProperties` to false and specify all provided fields as required (constraints of Structured Outputs). You don't need to pass these fields as part of your JSON schema. Twilio will automatically overwrite any user-provided values for these fields. + :ivar training_examples: An array of example input/output pairs used to illustrate the intended behavior of the Language Operator. These examples help guide the model's understanding of expected input–output relationships and improve consistency during evaluation and testing. **Note**: Training examples will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their training examples omitted from the API. + :ivar context: + :ivar parameters: Defines the schema of the parameters that are provided when running the operator, including required and optional values that determine the operator's behavior. The values of the parameters themselves are passed in by the attached Intelligence Configuration. + """ + + def __init__( + self, version: Version, payload: ResponseResource, id: Optional[str] = None + ): + super().__init__(version) + + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.http_status_code: Optional[int] = payload.get("httpStatusCode") + self.user_error: Optional[bool] = payload.get("userError") + self.params: Optional[Dict[str, str]] = payload.get("params") + self.id: Optional[str] = payload.get("id") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.author: Optional["OperatorInstance.OperatorAuthor"] = payload.get("author") + self.prompt: Optional[str] = payload.get("prompt") + self.output_format: Optional["OperatorInstance.str"] = payload.get( + "outputFormat" + ) + self.output_schema: Optional[Dict[str, object]] = payload.get("outputSchema") + self.training_examples: Optional[List[str]] = payload.get("trainingExamples") + self.context: Optional[str] = payload.get("context") + self.parameters: Optional[Dict[str, str]] = payload.get("parameters") + + # Only set _solution if path params are provided (not None) + if id is not None: + self._solution = { + "id": id, + } + + 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, + id=self._solution["id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the OperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OperatorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OperatorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> "OperatorInstance": + """ + Update the OperatorInstance + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: The updated OperatorInstance + """ + return self._proxy.update( + language_operator=language_operator, + if_match=if_match, + ) + + async def update_async( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> "OperatorInstance": + """ + Asynchronous coroutine to update the OperatorInstance + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: The updated OperatorInstance + """ + return await self._proxy.update_async( + language_operator=language_operator, + if_match=if_match, + ) + + def update_with_http_info( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the OperatorInstance with HTTP info + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + language_operator=language_operator, + if_match=if_match, + ) + + async def update_with_http_info_async( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the OperatorInstance with HTTP info + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + language_operator=language_operator, + 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 OperatorContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the OperatorContext + + :param version: Version that contains the resource + :param id: The unique identifier (TTID) of the Language Operator. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/ControlPlane/Operators/{id}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the OperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OperatorInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OperatorInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OperatorInstance: + """ + Fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + payload, _, _ = self._fetch() + return OperatorInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperatorInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OperatorInstance: + """ + Asynchronous coroutine to fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + payload, _, _ = await self._fetch_async() + return OperatorInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperatorInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = language_operator.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["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> OperatorInstance: + """ + Update the OperatorInstance + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: The updated OperatorInstance + """ + payload, _, _ = self._update( + language_operator=language_operator, if_match=if_match + ) + return OperatorInstance(self._version, payload, id=self._solution["id"]) + + def update_with_http_info( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the OperatorInstance and return response metadata + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + language_operator=language_operator, if_match=if_match + ) + instance = OperatorInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = language_operator.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["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> OperatorInstance: + """ + Asynchronous coroutine to update the OperatorInstance + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: The updated OperatorInstance + """ + payload, _, _ = await self._update_async( + language_operator=language_operator, if_match=if_match + ) + return OperatorInstance(self._version, payload, id=self._solution["id"]) + + async def update_with_http_info_async( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the OperatorInstance and return response metadata + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + language_operator=language_operator, if_match=if_match + ) + instance = OperatorInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, 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 OperatorPage(TokenPagination): + + 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): + + class LanguageOperator(object): + """ + :ivar id: The unique identifier for the Language Operator. Assigned by Twilio (TTID). + :ivar display_name: Display name of the Language Operator describing its purpose. + :ivar description: Description of the Language Operator further explaining its purpose. + :ivar version: Numeric Operator version. Automatically incremented with each update on the resource, used to ensure integrity when updating the Operator. + :ivar author: + :ivar prompt: The natural language instructions used by the operator to analyze the conversation. Within the prompt, users can reference parameters using the `{{parameters.[param_name]}}` syntax. Parameter values are provided to the Operator by the Intelligence Configuration Rule at runtime. **Note**: Prompts will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their prompts omitted from the API. + :ivar output_format: + :ivar output_schema: Required for `JSON` output only. this will be set to a JSON Schema object describing the properties & data types of the response. Please see https://platform.openai.com/docs/guides/structured-outputs#supported-schemas Will include the following keywords: - `type` : Must be set to `object` - `properties`: An object containing the property names and their data types you would like the LLM to return Additional details on JSON output formatting: - The root level `type` of a JSON schema must be set to `object` - The following property data types are supported : `string`, `number`, `boolean`, `integer`, `object`, `array`, `anyOf` - Definitions with `$defs` / `$ref` are supported - Max 100 object properties and 10 levels of nesting are supported - Max 1000 enum values across all enum properties are supported - Notable JSON Schema keywords not supported include: - For `strings`: `minLength`, `maxLength` - For `objects`: `patternProperties`, `unevaluatedProperties`, `propertyNames`, `minProperties`, `maxProperties` - For `arrays`: `unevaluatedItems`, `contains`, `minContains`, `maxContains`, `uniqueItems` - Structured Operator Results will be returned in the same order as the ordering of keys in the schema - In the event an Operator execution request is refused for safety reasons the Operator Result API response will include a new field called `refusal` to indicate that the LLM refused to fulfill the request - Twilio will automatically set `additionalProperties` to false and specify all provided fields as required (constraints of Structured Outputs). You don't need to pass these fields as part of your JSON schema. Twilio will automatically overwrite any user-provided values for these fields. + :ivar training_examples: An array of example input/output pairs used to illustrate the intended behavior of the Language Operator. These examples help guide the model's understanding of expected input–output relationships and improve consistency during evaluation and testing. **Note**: Training examples will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their training examples omitted from the API. + :ivar context: + :ivar parameters: Defines the schema of the parameters that are provided when running the operator, including required and optional values that determine the operator's behavior. The values of the parameters themselves are passed in by the attached Intelligence Configuration. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.author: Optional[OperatorAuthorEnum] = payload.get("author") + self.prompt: Optional[str] = payload.get("prompt") + self.output_format: Optional["OperatorInstance.OperatorOutputFormat"] = ( + payload.get("outputFormat") + ) + self.output_schema: Optional[Dict[str, object]] = payload.get( + "outputSchema" + ) + self.training_examples: Optional[ + List[OperatorList.OperatorTrainingExample] + ] = payload.get("trainingExamples") + self.context: Optional[OperatorList.OperatorContext] = payload.get( + "context" + ) + self.parameters: Optional[Dict[str, OperatorParameter]] = payload.get( + "parameters" + ) + + def to_dict(self): + return { + "id": self.id, + "displayName": self.display_name, + "description": self.description, + "version": self.version, + "author": self.author, + "prompt": self.prompt, + "outputFormat": self.output_format, + "outputSchema": self.output_schema, + "trainingExamples": ( + [ + training_examples.to_dict() + for training_examples in self.training_examples + ] + if self.training_examples is not None + else None + ), + "context": self.context.to_dict() if self.context is not None else None, + "parameters": ( + {k: v.to_dict() for k, v in self.parameters.items()} + if self.parameters is not None + else None + ), + } + + class OperatorContext(object): + """ + :ivar memory: + :ivar knowledge: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.memory: Optional[OperatorList.OperatorContextMemory] = payload.get( + "memory" + ) + self.knowledge: Optional[OperatorList.OperatorContextKnowledge] = ( + payload.get("knowledge") + ) + + def to_dict(self): + return { + "memory": self.memory.to_dict() if self.memory is not None else None, + "knowledge": ( + self.knowledge.to_dict() if self.knowledge is not None else None + ), + } + + class OperatorContextKnowledge(object): + """ + :ivar enabled: Set to true to allow access to Knowledge Sources at runtime. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.enabled: Optional[bool] = payload.get("enabled") + + def to_dict(self): + return { + "enabled": self.enabled, + } + + class OperatorContextMemory(object): + """ + :ivar enabled: Set to true to allow access to Memory at runtime. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.enabled: Optional[bool] = payload.get("enabled") + + def to_dict(self): + return { + "enabled": self.enabled, + } + + class OperatorTrainingExample(object): + """ + :ivar input: A sample input text that demonstrates the type of content the Operator processes. + :ivar output: The expected output corresponding to the provided input example. This value must be consistent with the defined `output_format` and `output_schema` of the Operator. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.input: Optional[str] = payload.get("input") + self.output: Optional[str] = payload.get("output") + + def to_dict(self): + return { + "input": self.input, + "output": self.output, + } + + def __init__(self, version: Version): + """ + Initialize the OperatorList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ControlPlane/Operators" + + def _create(self, language_operator: LanguageOperator) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = language_operator.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, language_operator: LanguageOperator) -> OperatorInstance: + """ + Create the OperatorInstance + + :param language_operator: Create Language Operator request + + :returns: The created OperatorInstance + """ + payload, _, _ = self._create(language_operator=language_operator) + return OperatorInstance(self._version, payload) + + def create_with_http_info(self, language_operator: LanguageOperator) -> ApiResponse: + """ + Create the OperatorInstance and return response metadata + + :param language_operator: Create Language Operator request + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + language_operator=language_operator + ) + instance = OperatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, language_operator: LanguageOperator) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = language_operator.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, language_operator: LanguageOperator + ) -> OperatorInstance: + """ + Asynchronously create the OperatorInstance + + :param language_operator: Create Language Operator request + + :returns: The created OperatorInstance + """ + payload, _, _ = await self._create_async(language_operator=language_operator) + return OperatorInstance(self._version, payload) + + async def create_with_http_info_async( + self, language_operator: LanguageOperator + ) -> ApiResponse: + """ + Asynchronously create the OperatorInstance and return response metadata + + :param language_operator: Create Language Operator request + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + language_operator=language_operator + ) + instance = OperatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: 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 str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_token=page_token, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: 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 str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OperatorInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OperatorInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: 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 str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: 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 str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OperatorInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OperatorInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> OperatorPage: + """ + Retrieve a single page of OperatorInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of OperatorInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-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, uri=self._uri, params=data) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> OperatorPage: + """ + Asynchronously retrieve a single page of OperatorInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of OperatorInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/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, uri=self._uri, params=data) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OperatorPage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, id: str) -> OperatorContext: + """ + Constructs a OperatorContext + + :param id: The unique identifier (TTID) of the Language Operator. + """ + return OperatorContext(self._version, id=id) + + def __call__(self, id: str) -> OperatorContext: + """ + Constructs a OperatorContext + + :param id: The unique identifier (TTID) of the Language Operator. + """ + return OperatorContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v3/operator_result.py b/twilio/rest/intelligence/v3/operator_result.py new file mode 100644 index 0000000000..1f649795d0 --- /dev/null +++ b/twilio/rest/intelligence/v3/operator_result.py @@ -0,0 +1,933 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Conversational Intelligence API + The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class OperatorResultInstance(InstanceResource): + """ + :ivar code: Twilio-specific error code + :ivar message: A human readable error message + :ivar http_status_code: HTTP response status code + :ivar user_error: Whether the error is a user error (true) or a system error (false) + :ivar params: A map of parameters related to the error, for example, a `params.twilioErrorCodeUrl` might hold a URL or link to additional information + :ivar output_format: The output format set on the Operator that generated this result. Determines the structure of the `result` object. + :ivar id: A unique identifier for the Operator Result. Assigned by Twilio (TTID). + :ivar account_id: The ID of the Account that created the Language Operator. + :ivar intelligence_configuration: + :ivar conversation_id: The `id` of the Conversation attached to the Operator Result. + :ivar operator: + :ivar date_created: Timestamp for when the Operator Result was created. + :ivar reference_ids: The `id`s of objects related to this Operator Result. + :ivar execution_details: + :ivar metadata: + :ivar result: + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + operator_result_id: Optional[str] = None, + ): + super().__init__(version) + + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.http_status_code: Optional[int] = payload.get("httpStatusCode") + self.user_error: Optional[bool] = payload.get("userError") + self.params: Optional[Dict[str, str]] = payload.get("params") + self.output_format: Optional[str] = payload.get("outputFormat") + self.id: Optional[str] = payload.get("id") + self.account_id: Optional[str] = payload.get("accountId") + self.intelligence_configuration: Optional[ + IntelligenceConfigurationReference + ] = payload.get("intelligenceConfiguration") + self.conversation_id: Optional[str] = payload.get("conversationId") + self.operator: Optional[OperatorReference] = payload.get("operator") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateCreated") + ) + self.reference_ids: Optional[List[str]] = payload.get("referenceIds") + self.execution_details: Optional[ExecutionDetails] = payload.get( + "executionDetails" + ) + self.metadata: Optional[OperatorResultsResponseBaseMetadata] = payload.get( + "metadata" + ) + self.result: Optional[ExtractionResultResult] = payload.get("result") + + # Only set _solution if path params are provided (not None) + if operator_result_id is not None: + self._solution = { + "operator_result_id": operator_result_id, + } + + 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, + operator_result_id=self._solution["operator_result_id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the OperatorResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OperatorResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OperatorResultInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OperatorResultInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "OperatorResultInstance": + """ + Fetch the OperatorResultInstance + + + :returns: The fetched OperatorResultInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperatorResultInstance": + """ + Asynchronous coroutine to fetch the OperatorResultInstance + + + :returns: The fetched OperatorResultInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorResultInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorResultInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 OperatorResultContext(InstanceContext): + + def __init__(self, version: Version, operator_result_id: str): + """ + Initialize the OperatorResultContext + + :param version: Version that contains the resource + :param operator_result_id: Operator Result id (TTID) + """ + super().__init__(version) + + # Path Solution + self._solution = { + "operator_result_id": operator_result_id, + } + self._uri = "/OperatorResults/{operator_result_id}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the OperatorResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OperatorResultInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OperatorResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OperatorResultInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OperatorResultInstance: + """ + Fetch the OperatorResultInstance + + + :returns: The fetched OperatorResultInstance + """ + payload, _, _ = self._fetch() + return OperatorResultInstance( + self._version, + payload, + operator_result_id=self._solution["operator_result_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorResultInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperatorResultInstance( + self._version, + payload, + operator_result_id=self._solution["operator_result_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OperatorResultInstance: + """ + Asynchronous coroutine to fetch the OperatorResultInstance + + + :returns: The fetched OperatorResultInstance + """ + payload, _, _ = await self._fetch_async() + return OperatorResultInstance( + self._version, + payload, + operator_result_id=self._solution["operator_result_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorResultInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperatorResultInstance( + self._version, + payload, + operator_result_id=self._solution["operator_result_id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 OperatorResultPage(TokenPagination): + + 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) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class OperatorResultList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperatorResultList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/OperatorResults" + + def stream( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, 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 str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, 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 str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OperatorResultInstance and returns headers from first page + + + :param str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OperatorResultInstance and returns headers from first page + + + :param str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, 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 str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, 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 str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OperatorResultInstance and returns headers from first page + + + :param str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OperatorResultInstance and returns headers from first page + + + :param str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> OperatorResultPage: + """ + Retrieve a single page of OperatorResultInstance records from the API. + Request is executed immediately + + :param conversation_id: Filter Operator Results by attached Conversation `id`. + :param intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param operator_id: Filter Operator Results by Language Operator `id`. + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of OperatorResultInstance + """ + data = values.of( + { + "conversationId": conversation_id, + "intelligenceConfigurationId": intelligence_configuration_id, + "operatorId": operator_id, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-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, uri=self._uri, params=data) + + async def page_async( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> OperatorResultPage: + """ + Asynchronously retrieve a single page of OperatorResultInstance records from the API. + Request is executed immediately + + :param conversation_id: Filter Operator Results by attached Conversation `id`. + :param intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param operator_id: Filter Operator Results by Language Operator `id`. + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of OperatorResultInstance + """ + data = values.of( + { + "conversationId": conversation_id, + "intelligenceConfigurationId": intelligence_configuration_id, + "operatorId": operator_id, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/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, uri=self._uri, params=data) + + def page_with_http_info( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param conversation_id: Filter Operator Results by attached Conversation `id`. + :param intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param operator_id: Filter Operator Results by Language Operator `id`. + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorResultPage, status code, and headers + """ + data = values.of( + { + "conversationId": conversation_id, + "intelligenceConfigurationId": intelligence_configuration_id, + "operatorId": operator_id, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OperatorResultPage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param conversation_id: Filter Operator Results by attached Conversation `id`. + :param intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param operator_id: Filter Operator Results by Language Operator `id`. + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorResultPage, status code, and headers + """ + data = values.of( + { + "conversationId": conversation_id, + "intelligenceConfigurationId": intelligence_configuration_id, + "operatorId": operator_id, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OperatorResultPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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) + + 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) + + def get(self, operator_result_id: str) -> OperatorResultContext: + """ + Constructs a OperatorResultContext + + :param operator_result_id: Operator Result id (TTID) + """ + return OperatorResultContext( + self._version, operator_result_id=operator_result_id + ) + + def __call__(self, operator_result_id: str) -> OperatorResultContext: + """ + Constructs a OperatorResultContext + + :param operator_result_id: Operator Result id (TTID) + """ + return OperatorResultContext( + self._version, operator_result_id=operator_result_id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v3/version.py b/twilio/rest/intelligence/v3/version.py new file mode 100644 index 0000000000..b283dbf541 --- /dev/null +++ b/twilio/rest/intelligence/v3/version.py @@ -0,0 +1,753 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Conversational Intelligence API + The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class VersionInstance(InstanceResource): + + class OperatorAuthor(object): + SELF = "SELF" + TWILIO = "TWILIO" + + class OperatorOutputFormat(object): + TEXT = "TEXT" + JSON = "JSON" + CLASSIFICATION = "CLASSIFICATION" + + class OperatorVersionStatus(object): + PREVIEW = "PREVIEW" + ACTIVE = "ACTIVE" + DEPRECATED = "DEPRECATED" + RETIRED = "RETIRED" + + """ + :ivar version: The numeric version number. + :ivar status: + :ivar date_created: Timestamp of when this version was created. + :ivar date_deprecated: Timestamp of when this version was deprecated. Present when status is `DEPRECATED` or `RETIRED`. + :ivar retirement_date: Scheduled retirement date for this version. Present when status is `DEPRECATED`. + :ivar date_retired: Timestamp of when this version was retired. Present when status is `RETIRED`. + :ivar id: The unique identifier for the Language Operator. Assigned by Twilio (TTID). + :ivar display_name: Display name of the Language Operator describing its purpose. + :ivar description: Description of the Language Operator further explaining its purpose. + :ivar author: + :ivar prompt: The natural language instructions used by the operator to analyze the conversation. Within the prompt, users can reference parameters using the `{{parameters.[param_name]}}` syntax. Parameter values are provided to the Operator by the Intelligence Configuration Rule at runtime. **Note**: Prompts will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their prompts omitted from the API. + :ivar output_format: + :ivar output_schema: Required for `JSON` output only. this will be set to a JSON Schema object describing the properties & data types of the response. Please see https://platform.openai.com/docs/guides/structured-outputs#supported-schemas Will include the following keywords: - `type` : Must be set to `object` - `properties`: An object containing the property names and their data types you would like the LLM to return Additional details on JSON output formatting: - The root level `type` of a JSON schema must be set to `object` - The following property data types are supported : `string`, `number`, `boolean`, `integer`, `object`, `array`, `anyOf` - Definitions with `$defs` / `$ref` are supported - Max 100 object properties and 10 levels of nesting are supported - Max 1000 enum values across all enum properties are supported - Notable JSON Schema keywords not supported include: - For `strings`: `minLength`, `maxLength` - For `objects`: `patternProperties`, `unevaluatedProperties`, `propertyNames`, `minProperties`, `maxProperties` - For `arrays`: `unevaluatedItems`, `contains`, `minContains`, `maxContains`, `uniqueItems` - Structured Operator Results will be returned in the same order as the ordering of keys in the schema - In the event an Operator execution request is refused for safety reasons the Operator Result API response will include a new field called `refusal` to indicate that the LLM refused to fulfill the request - Twilio will automatically set `additionalProperties` to false and specify all provided fields as required (constraints of Structured Outputs). You don't need to pass these fields as part of your JSON schema. Twilio will automatically overwrite any user-provided values for these fields. + :ivar training_examples: An array of example input/output pairs used to illustrate the intended behavior of the Language Operator. These examples help guide the model's understanding of expected input–output relationships and improve consistency during evaluation and testing. **Note**: Training examples will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their training examples omitted from the API. + :ivar context: + :ivar parameters: Defines the schema of the parameters that are provided when running the operator, including required and optional values that determine the operator's behavior. The values of the parameters themselves are passed in by the attached Intelligence Configuration. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + id: str, + resource_version: Optional[int] = None, + ): + super().__init__(version) + + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.status: Optional["VersionInstance.OperatorVersionStatus"] = payload.get( + "status" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateCreated") + ) + self.date_deprecated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateDeprecated") + ) + self.retirement_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("retirementDate") + ) + self.date_retired: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateRetired") + ) + self.id: Optional[str] = payload.get("id") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.author: Optional["VersionInstance.OperatorAuthor"] = payload.get("author") + self.prompt: Optional[str] = payload.get("prompt") + self.output_format: Optional["VersionInstance.str"] = payload.get( + "outputFormat" + ) + self.output_schema: Optional[Dict[str, object]] = payload.get("outputSchema") + self.training_examples: Optional[List[str]] = payload.get("trainingExamples") + self.context: Optional[str] = payload.get("context") + self.parameters: Optional[Dict[str, str]] = payload.get("parameters") + + # Only set _solution if path params are provided (not None) + if id is not None or resource_version is not None: + self._solution = { + "id": id, + "resource_version": resource_version, + } + + self._context: Optional[VersionContext] = None + + @property + def _proxy(self) -> "VersionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: VersionContext for this VersionInstance + """ + if self._context is None: + self._context = VersionContext( + self._version, + id=self._solution["id"], + resource_version=self._solution["resource_version"], + ) + return self._context + + def fetch(self) -> "VersionInstance": + """ + Fetch the VersionInstance + + + :returns: The fetched VersionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "VersionInstance": + """ + Asynchronous coroutine to fetch the VersionInstance + + + :returns: The fetched VersionInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 VersionContext(InstanceContext): + + def __init__(self, version: Version, id: str, resource_version: int): + """ + Initialize the VersionContext + + :param version: Version that contains the resource + :param id: The unique identifier (TTID) of the Language Operator. + :param resource_version: The numeric version number of the Language Operator. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + "resource_version": resource_version, + } + self._uri = "/ControlPlane/Operators/{id}/Versions/{resource_version}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> VersionInstance: + """ + Fetch the VersionInstance + + + :returns: The fetched VersionInstance + """ + payload, _, _ = self._fetch() + return VersionInstance( + self._version, + payload, + id=self._solution["id"], + resource_version=self._solution["resource_version"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VersionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = VersionInstance( + self._version, + payload, + id=self._solution["id"], + resource_version=self._solution["resource_version"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> VersionInstance: + """ + Asynchronous coroutine to fetch the VersionInstance + + + :returns: The fetched VersionInstance + """ + payload, _, _ = await self._fetch_async() + return VersionInstance( + self._version, + payload, + id=self._solution["id"], + resource_version=self._solution["resource_version"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VersionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = VersionInstance( + self._version, + payload, + id=self._solution["id"], + resource_version=self._solution["resource_version"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 VersionPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> VersionInstance: + """ + Build an instance of VersionInstance + + :param payload: Payload response from the API + """ + + return VersionInstance(self._version, payload, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class VersionList(ListResource): + + def __init__(self, version: Version, id: str): + """ + Initialize the VersionList + + :param version: Version that contains the resource + :param id: The unique identifier (TTID) of the Language Operator. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/ControlPlane/Operators/{id}/Versions".format(**self._solution) + + def stream( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[VersionInstance]: + """ + Streams VersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_token=page_token, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[VersionInstance]: + """ + Asynchronously streams VersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams VersionInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams VersionInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VersionInstance]: + """ + Lists VersionInstance 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: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VersionInstance]: + """ + Asynchronously lists VersionInstance 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: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists VersionInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists VersionInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> VersionPage: + """ + Retrieve a single page of VersionInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of VersionInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VersionPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> VersionPage: + """ + Asynchronously retrieve a single page of VersionInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of VersionInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VersionPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with VersionPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = VersionPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with VersionPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = VersionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> VersionPage: + """ + Retrieve a specific page of VersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VersionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return VersionPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> VersionPage: + """ + Asynchronously retrieve a specific page of VersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VersionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return VersionPage(self._version, response, solution=self._solution) + + def get(self, resource_version: int) -> VersionContext: + """ + Constructs a VersionContext + + :param resource_version: The numeric version number of the Language Operator. + """ + return VersionContext( + self._version, id=self._solution["id"], resource_version=resource_version + ) + + def __call__(self, resource_version: int) -> VersionContext: + """ + Constructs a VersionContext + + :param resource_version: The numeric version number of the Language Operator. + """ + return VersionContext( + self._version, id=self._solution["id"], resource_version=resource_version + ) + + 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 d06b3a44fe..b363627051 100644 --- a/twilio/rest/ip_messaging/v1/credential.py +++ b/twilio/rest/ip_messaging/v1/credential.py @@ -1,431 +1,907 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: + :ivar account_sid: + :ivar friendly_name: + :ivar type: + :ivar sandbox: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } - def __init__(self, version): + self._context: Optional[CredentialContext] = None + + @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 + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v1.credential.CredentialList - :rtype: twilio.rest.chat.v1.credential.CredentialList + def delete(self) -> bool: """ - super(CredentialList, self).__init__(version) + Deletes the CredentialInstance - # Path Solution - self._solution = {} - self._uri = '/Credentials'.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.chat.v1.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.credential.CredentialInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "CredentialInstance": """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + 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 self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance - return CredentialPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched CredentialInstance """ - Retrieve a specific page of CredentialInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info - :returns: Page of CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info - return CredentialPage(self._version, response, self._solution) - 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: ApiResponse with instance, status code, and headers """ - Create the CredentialInstance + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance - :param 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 + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - :returns: The created CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + :returns: The updated CredentialInstance """ - data = values.of({ - 'Type': type, - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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 - return CredentialInstance(self._version, payload, ) + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - def get(self, sid): + :returns: The updated CredentialInstance """ - Constructs a CredentialContext + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - :param sid: The unique string that identifies the resource + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + :returns: ApiResponse with instance, status code, and headers """ - return CredentialContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - def __call__(self, sid): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Constructs a CredentialContext + Asynchronous coroutine to update the CredentialInstance with HTTP info - :param sid: The unique string that identifies the resource + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + :returns: ApiResponse with instance, status code, and headers """ - return CredentialContext(self._version, sid=sid, ) + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialPage(Page): - """ """ +class CredentialContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the CredentialPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the CredentialContext - :returns: twilio.rest.chat.v1.credential.CredentialPage - :rtype: twilio.rest.chat.v1.credential.CredentialPage + :param version: Version that contains the resource + :param sid: """ - super(CredentialPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of CredentialInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.credential.CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + def delete(self) -> bool: """ - return CredentialInstance(self._version, payload, ) + Deletes the CredentialInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the CredentialInstance and return response metadata -class CredentialContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the CredentialContext - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource + headers = values.of({}) - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(CredentialContext, self).__init__(version) + Asynchronous coroutine that deletes the CredentialInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: """ Fetch the CredentialInstance + :returns: The fetched CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance and return response metadata - 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): + :returns: ApiResponse with instance, status code, and headers """ - Update the CredentialInstance + payload, status_code, headers = self._fetch() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :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 + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: The updated CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ - 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, ) + headers = values.of({}) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CredentialInstance: """ - Deletes the CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched CredentialInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, _, _ = await self._fetch_async() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the CredentialInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + payload, status_code, headers = await self._fetch_async() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + Returns: + tuple: (payload, status_code, headers) + """ -class CredentialInstance(InstanceResource): - """ """ + 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({}) - class PushService(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - def __init__(self, version, payload, sid=None): + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - Initialize the CredentialInstance + Update the CredentialInstance - :returns: twilio.rest.chat.v1.credential.CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance """ - super(CredentialInstance, self).__init__(version) + payload, _, _ = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CredentialInstance and return response metadata - # 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'), - } + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - 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 - :rtype: twilio.rest.chat.v1.credential.CredentialContext + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - if self._context is None: - self._context = CredentialContext(self._version, sid=self._solution['sid'], ) - return self._context + Asynchronous coroutine to update the CredentialInstance - @property - def sid(self): + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['sid'] + Asynchronous coroutine to update the CredentialInstance and return response metadata - @property - def account_sid(self): + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Provide a friendly representation + + :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 friendly_name(self): + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Build an instance of CredentialInstance + + :param payload: Payload response from the API """ - return self._properties['friendly_name'] - @property - def type(self): + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: """ - :returns: The type of push-notification service the credential is for - :rtype: CredentialInstance.PushService + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['type'] + return "" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource - @property - def sandbox(self): """ - :returns: [APN only] Whether to send the credential to sandbox APNs - :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, + ) -> tuple: """ - return self._properties['sandbox'] + Internal helper for create operation - @property - def date_created(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['date_created'] + Create the CredentialInstance - @property - def date_updated(self): + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Create the CredentialInstance and return response metadata - @property - def url(self): + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The absolute URL of the Credential resource - :rtype: unicode + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: """ - return self._properties['url'] + Internal async helper for create operation - def fetch(self): + Returns: + tuple: (payload, status_code, headers) """ - Fetch the CredentialInstance - :returns: The fetched CredentialInstance - :rtype: twilio.rest.chat.v1.credential.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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._proxy.fetch() + Asynchronously create the CredentialInstance - 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 type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance """ - Update the CredentialInstance + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata - :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 type: + :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 + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.update( + payload, status_code, headers = await self._create_async( + type=type, friendly_name=friendly_name, certificate=certificate, private_key=private_key, @@ -433,22 +909,394 @@ def update(self, friendly_name=values.unset, certificate=values.unset, api_key=api_key, secret=secret, ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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. - def delete(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 """ - Deletes the CredentialInstance + limits = self._version.read_limits(limit, page_size) + page = self.page(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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: """ - return self._proxy.delete() + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: + """ + return CredentialContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 f7d1225b9e..61c06df216 100644 --- a/twilio/rest/ip_messaging/v1/service/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/__init__.py @@ -1,913 +1,2640 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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, + } - def __init__(self, version): + self._context: Optional[ServiceContext] = None + + @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.chat.v1.service.ServiceList - :rtype: twilio.rest.chat.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 create(self, friendly_name): + :returns: True if delete succeeds, False otherwise """ - Create the ServiceInstance + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that 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, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info - return ServiceInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.ServiceInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: The updated ServiceInstance + """ + payload, _, _ = self._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 ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) + return self._channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + if self._roles is None: + self._roles = RoleList( + self._version, + self._solution["sid"], + ) + return self._roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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 """ - 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) + return ServiceInstance(self._version, payload) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.ServiceInstance] + 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 ServiceInstance records from the API. - Request is executed immediately + return "" - :param str page_token: PageToken provided by the API - :param int page_number: 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) +class ServiceList(ListResource): - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def __init__(self, version: Version): + """ + Initialize the ServiceList - return ServicePage(self._version, response, self._solution) + :param version: Version that contains the resource - def get_page(self, target_url): """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately + super().__init__(version) - :param str target_url: API-generated URL for the requested results page + self._uri = "/Services" - :returns: Page of ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServicePage + def _create(self, friendly_name: str) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + + data = values.of( + { + "FriendlyName": friendly_name, + } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - return ServicePage(self._version, response, self._solution) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def get(self, sid): + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, friendly_name: str) -> ServiceInstance: """ - Constructs a ServiceContext + Create the ServiceInstance - :param sid: The unique string that identifies the resource + :param friendly_name: - :returns: twilio.rest.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + :returns: The created ServiceInstance """ - return ServiceContext(self._version, sid=sid, ) + payload, _, _ = self._create(friendly_name=friendly_name) + return ServiceInstance(self._version, payload) - def __call__(self, sid): + def create_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Constructs a ServiceContext + Create the ServiceInstance and return response metadata - :param sid: The unique string that identifies the resource + :param friendly_name: - :returns: twilio.rest.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + :returns: ApiResponse with instance, status code, and headers """ - return ServiceContext(self._version, sid=sid, ) + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _create_async(self, friendly_name: str) -> tuple: """ - Provide a friendly representation + Internal async helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class ServicePage(Page): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, response, solution): - """ - Initialize the ServicePage + headers["Accept"] = "application/json" - :param Version version: Version that contains the resource - :param Response response: Response from the API + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.chat.v1.service.ServicePage - :rtype: twilio.rest.chat.v1.service.ServicePage + async def create_async(self, friendly_name: str) -> ServiceInstance: """ - super(ServicePage, self).__init__(version, response) + Asynchronously create the ServiceInstance - # Path Solution - self._solution = solution + :param friendly_name: - def get_instance(self, payload): + :returns: The created ServiceInstance """ - Build an instance of ServiceInstance + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return ServiceInstance(self._version, payload) - :param dict payload: Payload response from the API - - :returns: twilio.rest.chat.v1.service.ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: """ - return ServiceInstance(self._version, payload, ) + Asynchronously create the ServiceInstance and return response metadata - def __repr__(self): - """ - Provide a friendly representation + :param friendly_name: - :returns: Machine friendly representation - :rtype: str + :returns: ApiResponse with instance, status code, and headers """ - return '' + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + 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. -class ServiceContext(InstanceContext): - """ """ + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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, sid): + :returns: Generator that will yield up to limit results """ - Initialize the ServiceContext + 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 sid: The unique string that identifies the resource + return self._version.stream(page, limits["limit"]) - :returns: twilio.rest.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: """ - super(ServiceContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) + 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. - # Dependents - self._channels = None - self._roles = None - self._users = None + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def fetch(self): + :returns: Generator that will yield up to limit results """ - Fetch the ServiceInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :returns: The fetched ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Streams ServiceInstance and returns headers from first page - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - def delete(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: tuple of (generator, status_code, headers) where generator yields instances """ - Deletes the ServiceInstance + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - :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): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Update the ServiceInstance + Asynchronously streams ServiceInstance and returns headers from first page - :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 - :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'], ) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 channels(self): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Access the channels + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :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'], ) - return self._channels + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - @property - def roles(self): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: """ - Access the roles + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: 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'], ) - return self._roles + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 users(self): + :returns: list that will contain up to limit results """ - 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'], ) - return self._users + 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[ServiceInstance]: """ - Provide a friendly representation + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: Machine friendly representation - :rtype: str + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] -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'), - } + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page - # 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 + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceContext + :returns: ApiResponse with list of instances, status code, and headers """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Asynchronously lists ServiceInstance and returns headers from first page - @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'] + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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_created(self): + :returns: ApiResponse with list of instances, status code, and headers """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + 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: """ - return self._properties['date_updated'] + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - @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 page_token: PageToken provided by the 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 default_channel_role_sid(self): - """ - :returns: The channel role assigned to users when they are added to a channel - :rtype: unicode + :returns: Page of ServiceInstance """ - return self._properties['default_channel_role_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @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'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def read_status_enabled(self): - """ - :returns: Whether the Message Consumption Horizon feature is enabled - :rtype: bool - """ - return self._properties['read_status_enabled'] + headers["Accept"] = "application/json" - @property - def reachability_enabled(self): - """ - :returns: Whether the Reachability Indicator feature is enabled for this Service instance - :rtype: bool - """ - return self._properties['reachability_enabled'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) - @property - def typing_indicator_timeout(self): + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: """ - :returns: How long in seconds to wait before assuming the user is no longer typing - :rtype: unicode - """ - return self._properties['typing_indicator_timeout'] + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - @property - def consumption_report_interval(self): - """ - :returns: DEPRECATED - :rtype: unicode - """ - return self._properties['consumption_report_interval'] + :param page_token: PageToken provided by the 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 limits(self): - """ - :returns: An object that describes the limits of the service instance - :rtype: dict + :returns: Page of ServiceInstance """ - return self._properties['limits'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def webhooks(self): - """ - :returns: An object that contains information about the webhooks configured for this service - :rtype: dict - """ - return self._properties['webhooks'] + headers = values.of({"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'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) - @property - def webhook_method(self): + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The HTTP method to use for both PRE and POST webhooks - :rtype: unicode - """ - return self._properties['webhook_method'] + Retrieve a single page with response metadata - @property - def webhook_filters(self): - """ - :returns: The list of WebHook events that are enabled for this Service instance - :rtype: unicode - """ - return self._properties['webhook_filters'] - @property - def notifications(self): - """ - :returns: The notification configuration for the Service instance - :rtype: dict - """ - return self._properties['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 - @property - def url(self): + :returns: ApiResponse with ServicePage, status code, and headers """ - :returns: The absolute URL of the Service resource - :rtype: unicode - """ - return self._properties['url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def links(self): - """ - :returns: The absolute URLs of the Service's Channels, Roles, and Users - :rtype: unicode - """ - return self._properties['links'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def fetch(self): - """ - Fetch the ServiceInstance + headers["Accept"] = "application/json" - :returns: The fetched ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance - """ - return self._proxy.fetch() + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - def delete(self): + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the ServiceInstance + Asynchronously retrieve a single page with response metadata - :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: ApiResponse with ServicePage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - 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): + 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 + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.chat.v1.service.channel.ChannelList - :rtype: twilio.rest.chat.v1.service.channel.ChannelList + :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 2e77f25923..bca3bc717b 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/channel/__init__.py @@ -1,598 +1,1329 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page from twilio.rest.ip_messaging.v1.service.channel.invite import InviteList from twilio.rest.ip_messaging.v1.service.channel.member import MemberList from twilio.rest.ip_messaging.v1.service.channel.message import MessageList -class ChannelList(ListResource): - """ """ +class ChannelInstance(InstanceResource): + + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar friendly_name: + :ivar unique_name: + :ivar attributes: + :ivar type: + :ivar date_created: + :ivar date_updated: + :ivar created_by: + :ivar members_count: + :ivar messages_count: + :ivar url: + :ivar links: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.type: Optional["ChannelInstance.ChannelType"] = payload.get("type") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.members_count: Optional[int] = deserialize.integer( + payload.get("members_count") + ) + self.messages_count: Optional[int] = deserialize.integer( + payload.get("messages_count") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } - def __init__(self, version, service_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 - :param service_sid: The SID of the Service that the resource is associated with + :returns: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v1.service.channel.ChannelList - :rtype: twilio.rest.chat.v1.service.channel.ChannelList + def delete(self) -> bool: """ - super(ChannelList, self).__init__(version) + Deletes the ChannelInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Channels'.format(**self._solution) - def create(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset, type=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the ChannelInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance - :returns: The created ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: """ - data = values.of({ - 'FriendlyName': friendly_name, - 'UniqueName': unique_name, - 'Attributes': attributes, - 'Type': type, - }) + Deletes the ChannelInstance with HTTP info - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() - def stream(self, type=values.unset, limit=None, page_size=None): + async def delete_with_http_info_async(self) -> ApiResponse: """ - 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. + Asynchronous coroutine that deletes the ChannelInstance with HTTP info - :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) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.ChannelInstance] + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(type=type, page_size=limits['page_size'], ) + def fetch(self) -> "ChannelInstance": + """ + Fetch the ChannelInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, type=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelInstance": + """ + Asynchronous coroutine to 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 await self._proxy.fetch_async() - def page(self, type=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of ChannelInstance records from the API. - Request is executed immediately + Fetch the ChannelInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Type': serialize.map(type, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance with HTTP info - return ChannelPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of ChannelInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Update the ChannelInstance - :returns: Page of ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelPage + :param friendly_name: + :param unique_name: + :param attributes: + + :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) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Asynchronous coroutine to update the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: - def get(self, sid): + :returns: The updated ChannelInstance """ - Constructs a ChannelContext + return await self._proxy.update_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) - :param sid: The unique string that identifies the resource + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Constructs a ChannelContext + Asynchronous coroutine to update the ChannelInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + return self._proxy.invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + return self._proxy.members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages - def __repr__(self): + 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) + + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of ChannelInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.service.channel.ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + def delete(self) -> bool: """ - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the ChannelInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the ChannelInstance and return response metadata -class ChannelContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the ChannelContext - :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 + headers = values.of({}) - :returns: twilio.rest.chat.v1.service.channel.ChannelContext - :rtype: twilio.rest.chat.v1.service.channel.ChannelContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(ChannelContext, self).__init__(version) + Asynchronous coroutine that deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance and return response metadata - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Channels/{sid}'.format(**self._solution) - # Dependents - self._members = None - self._messages = None - self._invites = None + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def fetch(self): + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: """ Fetch the ChannelInstance + :returns: The fetched ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + :returns: The fetched ChannelInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the ChannelInstance + Asynchronous coroutine to fetch the ChannelInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + } + ) + headers = values.of({}) - def update(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: """ Update the ChannelInstance - :param 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._update( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance and return response metadata + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + :returns: The updated ChannelInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) return ChannelInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance and return response metadata + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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) + - def __repr__(self): +class ChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: + """ + Build an instance of ChannelInstance + + :param payload: Payload response from the API + """ + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class ChannelInstance(InstanceResource): - """ """ +class ChannelList(ListResource): - class ChannelType(object): - PUBLIC = "public" - PRIVATE = "private" + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ChannelList - 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'), - } + :param version: Version that contains the resource + :param service_sid: - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + """ + super().__init__(version) - @property - def _proxy(self): + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Channels".format(**self._solution) + + def _create( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> tuple: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Internal helper for create operation - :returns: ChannelContext for this ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelContext + Returns: + tuple: (payload, status_code, headers) """ - if self._context is None: - self._context = ChannelContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context - @property - def sid(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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Create the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + + :returns: The created ChannelInstance """ - return self._properties['sid'] + payload, _, _ = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def account_sid(self): + def create_with_http_info( + 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, + ) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Create the ChannelInstance and return response metadata + + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['account_sid'] + payload, status_code, headers = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def service_sid(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, + ) -> tuple: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['service_sid'] - @property - def friendly_name(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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 string that you assigned to describe the resource - :rtype: unicode + Asynchronously create the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + + :returns: The created ChannelInstance """ - return self._properties['friendly_name'] + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def unique_name(self): + async def create_with_http_info_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, + ) -> ApiResponse: """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + Asynchronously create the ChannelInstance and return response metadata + + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['unique_name'] + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def attributes(self): + def stream( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: """ - :returns: The JSON string that stores application-specific data - :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['attributes'] + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) - @property - def type(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 visibility of the channel. Can be: `public` or `private` - :rtype: ChannelInstance.ChannelType + 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['type'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) - @property - def date_created(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + Streams ChannelInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + type=type, page_size=limits["page_size"] + ) - @property - def date_updated(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + Asynchronously streams ChannelInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + type=type, page_size=limits["page_size"] + ) - @property - def created_by(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: """ - :returns: The identity of the User that created 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 self._properties['created_by'] - @property - def members_count(self): + 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]: """ - :returns: The number of Members in the Channel - :rtype: unicode + Asynchronously lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['members_count'] - @property - def messages_count(self): + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The number of Messages in the Channel - :rtype: unicode + Lists ChannelInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers """ - return self._properties['messages_count'] + generator, status_code, headers = self.stream_with_http_info( + type=type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def url(self): + async def list_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The absolute URL of the Channel resource - :rtype: unicode + Asynchronously lists ChannelInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers """ - return self._properties['url'] + generator, status_code, headers = await self.stream_with_http_info_async( + type=type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def links(self): + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: """ - :returns: Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel - :rtype: unicode + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance """ - return self._properties['links'] + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def fetch(self): + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, solution=self._solution) + + async def page_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: """ - Fetch the ChannelInstance + Asynchronously 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, solution=self._solution) - def delete(self): + def page_with_http_info( + 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, + ) -> ApiResponse: """ - Deletes the ChannelInstance + Retrieve a single page with response metadata - :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: ApiResponse with ChannelPage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ChannelPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - 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, solution=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, solution=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 bfa8ae61e2..f0b7e70c47 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/invite.py +++ b/twilio/rest/ip_messaging/v1/service/channel/invite.py @@ -1,448 +1,985 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 + return self._proxy.delete() - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The Role assigned to the new member + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance - :returns: The created InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + + :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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance with HTTP info - return InviteInstance( - 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: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.invite.InviteInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "InviteInstance": + """ + Fetch the InviteInstance - page = self.page(identity=identity, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched InviteInstance + """ + return self._proxy.fetch() - def list(self, identity=values.unset, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to 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. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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 """ - return list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of InviteInstance records from the API. - Request is executed immediately + Fetch the InviteInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance with HTTP info - return InvitePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of InviteInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InvitePage + :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 InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the InviteContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Invites/{sid}".format( + **self._solution + ) ) - return InvitePage(self._version, response, self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation - def get(self, sid): + Returns: + tuple: (success_boolean, status_code, headers) """ - Constructs a InviteContext - :param sid: The unique string that identifies the resource + headers = values.of({}) - :returns: twilio.rest.chat.v1.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteContext + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return InviteContext( + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + payload, _, _ = self._fetch() + 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 __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a InviteContext + Fetch the InviteInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return InviteContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class InvitePage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> InviteInstance: """ - Initialize the InvitePage + Asynchronous coroutine to fetch the InviteInstance + - :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 + :returns: The fetched InviteInstance + """ + payload, _, _ = await self._fetch_async() + 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 + async def fetch_with_http_info_async(self) -> ApiResponse: """ - super(InvitePage, self).__init__(version, response) + Asynchronous coroutine to fetch the InviteInstance and return response metadata - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of InviteInstance + payload, status_code, headers = await self._fetch_async() + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.chat.v1.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + :returns: Machine friendly representation """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: + """ + Build an instance of InviteInstance + + :param payload: Payload response from the API + """ + return InviteInstance( self._version, payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + 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 + ) -> tuple: """ - Fetch the InviteInstance + Internal helper for create operation - :returns: The fetched InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: + :param role_sid: + + :returns: The created InviteInstance + """ + payload, _, _ = self._create(identity=identity, role_sid=role_sid) 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): + def create_with_http_info( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: """ - Deletes the InviteInstance + Create the InviteInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param identity: + :param role_sid: + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: """ - Provide a friendly representation + Internal async helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - 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"}) -class InviteInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, payload, service_sid, channel_sid, sid=None): + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: """ - Initialize the InviteInstance + Asynchronously create the InviteInstance + + :param identity: + :param role_sid: - :returns: twilio.rest.chat.v1.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + :returns: The created InviteInstance """ - super(InviteInstance, self).__init__(version) + payload, _, _ = await self._create_async(identity=identity, role_sid=role_sid) + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - # 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'), - } + async def create_with_http_info_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the InviteInstance and return response metadata - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + :param identity: + :param role_sid: - @property - def _proxy(self): + :returns: ApiResponse with instance, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, status_code, headers = await self._create_async( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: InviteContext for this InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteContext + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[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 + 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 sid(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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InviteInstance]: """ - return self._properties['sid'] + 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 account_sid(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 """ - :returns: The SID of the Account that created the resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['account_sid'] + Streams InviteInstance and returns headers from first page - @property - def channel_sid(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The SID of the Channel the new resource belongs to - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['channel_sid'] + Asynchronously streams InviteInstance and returns headers from first page - @property - def service_sid(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - return self._properties['service_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. - @property - def identity(self): + :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 """ - :returns: The string that identifies the resource's User - :rtype: unicode + + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - return self._properties['identity'] + 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 date_created(self): + :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 """ - :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( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_created'] + Lists InviteInstance and returns headers from first page - @property - def date_updated(self): + + :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: ApiResponse with list of instances, status code, and headers """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously lists InviteInstance and returns headers from first page - @property - def role_sid(self): + + :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: ApiResponse with list of instances, status code, and headers """ - :returns: The SID of the Role assigned to the member - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['role_sid'] + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately - @property - def created_by(self): + :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 """ - :returns: The identity of the User that created the invite - :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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, solution=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: """ - return self._properties['created_by'] + Asynchronously retrieve a single page of InviteInstance records from the API. + Request is executed immediately - @property - def url(self): + :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 """ - :returns: The absolute URL of the Invite 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 InvitePage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['url'] + Retrieve a single page with response metadata + + + :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 - def fetch(self): + :returns: ApiResponse with InvitePage, status code, and headers """ - Fetch the InviteInstance + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: The fetched InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with InvitePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> InvitePage: """ - return self._proxy.fetch() + Retrieve a specific page of InviteInstance 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 InviteInstance """ - Deletes the InviteInstance + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, solution=self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def get_page_async(self, target_url: str) -> InvitePage: """ - return self._proxy.delete() + Asynchronously retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 ff25b12dbd..6dccde7822 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/member.py +++ b/twilio/rest/ip_messaging/v1/service/channel/member.py @@ -1,496 +1,1217 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class MemberList(ListResource): - """ """ +class MemberInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar channel_sid: + :ivar service_sid: + :ivar identity: + :ivar date_created: + :ivar date_updated: + :ivar role_sid: + :ivar last_consumed_message_index: + :ivar last_consumption_timestamp: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } - def __init__(self, version, service_sid, channel_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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MemberInstance with HTTP info - 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: ApiResponse with success boolean, status code, and headers """ - 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.delete_with_http_info() - :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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.member.MemberInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(identity=identity, page_size=limits['page_size'], ) + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, identity=values.unset, limit=None, page_size=None): + :returns: The fetched MemberInstance """ - Lists MemberInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return 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. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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) -> "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 """ - return list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of MemberInstance records from the API. - Request is executed immediately + Fetch the MemberInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance with HTTP info - return MemberPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of MemberInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance - :returns: Page of MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberPage + :param role_sid: + :param last_consumed_message_index: + + :returns: The updated MemberInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, ) - return MemberPage(self._version, response, self._solution) + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> "MemberInstance": + """ + Asynchronous coroutine to update the MemberInstance + + :param role_sid: + :param last_consumed_message_index: - def get(self, sid): + :returns: The updated MemberInstance """ - Constructs a MemberContext + return await self._proxy.update_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the MemberInstance with HTTP info - :param sid: The unique string that identifies the resource + :param role_sid: + :param last_consumed_message_index: - :returns: twilio.rest.chat.v1.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + :returns: ApiResponse with instance, status code, and headers """ - return MemberContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + return self._proxy.update_with_http_info( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Constructs a MemberContext + Asynchronous coroutine to update the MemberInstance with HTTP info - :param sid: The unique string that identifies the resource + :param role_sid: + :param last_consumed_message_index: - :returns: twilio.rest.chat.v1.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + :returns: ApiResponse with instance, status code, and headers """ - return MemberContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + return await self._proxy.update_with_http_info_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, ) - 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 MemberPage(Page): - """ """ +class MemberContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - 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 unique ID of the Channel for the member + Initialize the MemberContext - :returns: twilio.rest.chat.v1.service.channel.member.MemberPage - :rtype: twilio.rest.chat.v1.service.channel.member.MemberPage + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: """ - super(MemberPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of MemberInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.service.channel.member.MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + def delete(self) -> bool: """ - return MemberInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + Deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MemberInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the MemberInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance and return response metadata -class MemberContext(InstanceContext): - """ """ - def __init__(self, version, service_sid, channel_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the MemberContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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 unique ID of the channel the member belongs to - :param sid: The unique string that identifies the resource + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.chat.v1.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + Returns: + tuple: (payload, status_code, headers) """ - super(MemberContext, 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}/Members/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> MemberInstance: """ Fetch the MemberInstance + :returns: The fetched MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + payload, _, _ = await self._fetch_async() 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"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the MemberInstance + Asynchronous coroutine to fetch the MemberInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, role_sid=values.unset, - last_consumed_message_index=values.unset): + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> 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 + :param role_sid: + :param last_consumed_message_index: :returns: The updated MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance """ - data = values.of({'RoleSid': role_sid, 'LastConsumedMessageIndex': last_consumed_message_index, }) + payload, _, _ = self._update( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the MemberInstance and return response metadata + + :param role_sid: + :param last_consumed_message_index: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :param role_sid: + :param last_consumed_message_index: + :returns: The updated MemberInstance + """ + payload, _, _ = await self._update_async( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) 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"], + sid=self._solution["sid"], ) - def __repr__(self): + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance and return response metadata + + :param role_sid: + :param last_consumed_message_index: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide 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 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'), - } +class MemberPage(Page): - # Context - self._context = None + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: + """ + Build an instance of MemberInstance + + :param payload: Payload response from the API + """ + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MemberList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MemberList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "channel_sid": channel_sid, } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) - @property - def _proxy(self): + def _create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Internal helper for create operation - :returns: MemberContext for this MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + Returns: + tuple: (payload, status_code, headers) """ - 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 - @property - def sid(self): + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Create the MemberInstance + + :param identity: + :param role_sid: + + :returns: The created MemberInstance """ - return self._properties['sid'] + payload, _, _ = self._create(identity=identity, role_sid=role_sid) + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def account_sid(self): + def create_with_http_info( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Create the MemberInstance and return response metadata + + :param identity: + :param role_sid: + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['account_sid'] + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def channel_sid(self): + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: """ - :returns: The unique ID of the Channel for the member - :rtype: unicode + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['channel_sid'] - @property - def service_sid(self): + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + Asynchronously create the MemberInstance + + :param identity: + :param role_sid: + + :returns: The created MemberInstance """ - return self._properties['service_sid'] + payload, _, _ = await self._create_async(identity=identity, role_sid=role_sid) + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def identity(self): + async def create_with_http_info_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: """ - :returns: The string that identifies the resource's User - :rtype: unicode + Asynchronously create the MemberInstance and return response metadata + + :param identity: + :param role_sid: + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['identity'] + payload, status_code, headers = await self._create_async( + identity=identity, role_sid=role_sid + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def date_created(self): + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + Streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) - @property - def date_updated(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + Asynchronously streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) - @property - def role_sid(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Role assigned to the member - :rtype: unicode + Streams MemberInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['role_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) - @property - def last_consumed_message_index(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The index of the last Message that the Member has read within the Channel - :rtype: unicode + Asynchronously streams MemberInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['last_consumed_message_index'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) - @property - def last_consumption_timestamp(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - :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 + 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 self._properties['last_consumption_timestamp'] - @property - def url(self): + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - :returns: The absolute URL of the Member resource - :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 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 self._properties['url'] - def fetch(self): + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Fetch the MemberInstance + Lists MemberInstance and returns headers from first page - :returns: The fetched MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + + :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: ApiResponse with list of instances, status code, and headers """ - return self._proxy.fetch() + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - def delete(self): + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Deletes the MemberInstance + Asynchronously lists MemberInstance and returns headers from first page - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :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: ApiResponse with list of instances, status code, and headers """ - return self._proxy.delete() + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - def update(self, role_sid=values.unset, - last_consumed_message_index=values.unset): + 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: """ - Update the MemberInstance + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately - :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 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: The updated MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + :returns: Page of MemberInstance """ - return self._proxy.update( - role_sid=role_sid, - last_consumed_message_index=last_consumed_message_index, + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, solution=self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with MemberPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with MemberPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> MemberPage: + """ + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> MemberPage: + """ + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 1f007dd2a2..6d0ba2da88 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/message.py +++ b/twilio/rest/ip_messaging/v1/service/channel/message.py @@ -1,513 +1,1242 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class MessageList(ListResource): - """ """ +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + """ + :ivar sid: + :ivar account_sid: + :ivar attributes: + :ivar service_sid: + :ivar to: + :ivar channel_sid: + :ivar date_created: + :ivar date_updated: + :ivar was_edited: + :ivar _from: + :ivar body: + :ivar index: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.service_sid: Optional[str] = payload.get("service_sid") + self.to: Optional[str] = payload.get("to") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.was_edited: Optional[bool] = payload.get("was_edited") + self._from: Optional[str] = payload.get("from") + self.body: Optional[str] = payload.get("body") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } - def __init__(self, version, service_sid, channel_sid): + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": """ - Initialize the MessageList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The 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: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v1.service.channel.message.MessageList - :rtype: twilio.rest.chat.v1.service.channel.message.MessageList + def delete(self) -> bool: """ - super(MessageList, self).__init__(version) + Deletes the MessageInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'channel_sid': channel_sid, } - self._uri = '/Services/{service_sid}/Channels/{channel_sid}/Messages'.format(**self._solution) - def create(self, body, from_=values.unset, attributes=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the MessageInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance - :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 await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info - 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: ApiResponse with success boolean, status code, and headers """ - Streams MessageInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + return self._proxy.delete_with_http_info() - :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) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.message.MessageInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(order=order, page_size=limits['page_size'], ) + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, order=values.unset, limit=None, page_size=None): + :returns: The fetched MessageInstance """ - Lists MessageInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + 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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately + Fetch the MessageInstance with HTTP info - :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.v1.service.channel.message.MessagePage + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Order': order, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info - return MessagePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + 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 self._proxy.update( + body=body, + attributes=attributes, ) - return MessagePage(self._version, response, self._solution) + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance - def get(self, sid): + :param body: + :param attributes: + + :returns: The updated MessageInstance """ - Constructs a MessageContext + return await self._proxy.update_async( + body=body, + attributes=attributes, + ) + + def update_with_http_info( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return MessageContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + return self._proxy.update_with_http_info( + body=body, + attributes=attributes, ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Constructs a MessageContext + Asynchronous coroutine to update the MessageInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return MessageContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + return await self._proxy.update_with_http_info_async( + body=body, + attributes=attributes, ) - 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, service_sid: str, channel_sid: str, sid: str): """ - Initialize the MessagePage - - :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 + Initialize the MessageContext - :returns: twilio.rest.chat.v1.service.channel.message.MessagePage - :rtype: twilio.rest.chat.v1.service.channel.message.MessagePage + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: """ - super(MessagePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of MessageInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.service.channel.message.MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + def delete(self) -> bool: """ - return MessageInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + Deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessageInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + 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 '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance and return response metadata -class MessageContext(InstanceContext): - """ """ - def __init__(self, version, service_sid, channel_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the MessageContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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 unique ID of the Channel the message to fetch belongs to - :param sid: The unique string that identifies the resource + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.chat.v1.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext + Returns: + tuple: (payload, status_code, headers) """ - 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) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: """ Fetch the MessageInstance + :returns: The fetched MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the MessageInstance + Asynchronous coroutine to fetch the MessageInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for update operation - def update(self, body=values.unset, attributes=values.unset): + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ 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 + :param body: + :param attributes: :returns: The updated MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance """ - data = values.of({'Body': body, 'Attributes': attributes, }) + payload, _, _ = self._update(body=body, attributes=attributes) + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance and return response metadata + + :param body: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(body=body, attributes=attributes) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param body: + :param attributes: + + :returns: The updated MessageInstance + """ + payload, _, _ = await self._update_async(body=body, attributes=attributes) 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"], + ) + + async def update_with_http_info_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance and return response metadata + + :param body: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + body=body, attributes=attributes + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class MessageInstance(InstanceResource): - """ """ +class MessagePage(Page): - class OrderType(object): - ASC = "asc" - DESC = "desc" + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance - 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 payload: Payload response from the API + """ + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - # Context - self._context = None + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MessageList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - '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, + ) -> tuple: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Internal helper for create operation - :returns: MessageContext for this MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext + Returns: + tuple: (payload, status_code, headers) """ - 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 - @property - def sid(self): + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Create the MessageInstance + + :param body: + :param from_: + :param attributes: + + :returns: The created MessageInstance """ - return self._properties['sid'] + payload, _, _ = self._create(body=body, from_=from_, attributes=attributes) + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def account_sid(self): + def create_with_http_info( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Create the MessageInstance and return response metadata + + :param body: + :param from_: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['account_sid'] + payload, status_code, headers = self._create( + body=body, from_=from_, attributes=attributes + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def attributes(self): + async def _create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: """ - :returns: The JSON string that stores application-specific data - :rtype: unicode + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['attributes'] - @property - def service_sid(self): + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + Asynchronously create the MessageInstance + + :param body: + :param from_: + :param attributes: + + :returns: The created MessageInstance """ - return self._properties['service_sid'] + payload, _, _ = await self._create_async( + body=body, from_=from_, attributes=attributes + ) + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def to(self): + async def create_with_http_info_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: """ - :returns: The SID of the Channel that the message was sent to - :rtype: unicode + Asynchronously create the MessageInstance and return response metadata + + :param body: + :param from_: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['to'] + payload, status_code, headers = await self._create_async( + body=body, from_=from_, attributes=attributes + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def channel_sid(self): + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: """ - :returns: The unique ID of the Channel the Message resource belongs to - :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['channel_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) - @property - def date_created(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 RFC 2822 date and time in GMT when the resource was created - :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: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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(order=order, page_size=limits["page_size"]) - @property - def date_updated(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + Streams MessageInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + order=order, page_size=limits["page_size"] + ) - @property - def was_edited(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: Whether the message has been edited since it was created - :rtype: bool + Asynchronously streams MessageInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['was_edited'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + order=order, page_size=limits["page_size"] + ) - @property - def from_(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - :returns: The identity of the message's author - :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 self._properties['from_'] - @property - def body(self): + 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 self._properties['body'] - @property - def index(self): + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The index of the message within the Channel - :rtype: unicode + Lists MessageInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers """ - return self._properties['index'] + generator, status_code, headers = self.stream_with_http_info( + order=order, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def url(self): + async def list_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The absolute URL of the Message resource - :rtype: unicode + Asynchronously lists MessageInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers """ - return self._properties['url'] + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - def fetch(self): + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: """ - Fetch the MessageInstance + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately - :returns: The fetched MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + :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._proxy.fetch() + 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, solution=self._solution) - def delete(self): + 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: """ - Deletes the MessageInstance + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._proxy.delete() + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def update(self, body=values.unset, attributes=values.unset): + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: """ - Update the MessageInstance + Retrieve a single page with response metadata - :param unicode body: The message to send to the channel - :param unicode attributes: A valid JSON string that contains application-specific data - :returns: The updated MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + :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: ApiResponse with MessagePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with MessagePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :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 __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 d9bbaf206b..e7156129ef 100644 --- a/twilio/rest/ip_messaging/v1/service/role.py +++ b/twilio/rest/ip_messaging/v1/service/role.py @@ -1,442 +1,1086 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class RoleList(ListResource): - """ """ +class RoleInstance(InstanceResource): + + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar friendly_name: + :ivar type: + :ivar permissions: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } - def __init__(self, version, service_sid): + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": """ - Initialize the RoleList + 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: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v1.service.role.RoleList - :rtype: twilio.rest.chat.v1.service.role.RoleList + def delete(self) -> bool: """ - super(RoleList, self).__init__(version) + Deletes the RoleInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Roles'.format(**self._solution) - def create(self, friendly_name, type, permission): + :returns: True if delete succeeds, False otherwise """ - Create the RoleInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance - :returns: The created RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Type': type, - 'Permission': serialize.map(permission, lambda e: e), - }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.role.RoleInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.role.RoleInstance] + + :returns: The fetched RoleInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of RoleInstance records from the API. - Request is executed immediately + Fetch the RoleInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info - return RolePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of RoleInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance - :param str target_url: API-generated URL for the requested results page + :param permission: - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RolePage + :returns: The updated RoleInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + permission=permission, ) - return RolePage(self._version, response, self._solution) + async def update_async(self, permission: List[str]) -> "RoleInstance": + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: - def get(self, sid): + :returns: The updated RoleInstance """ - Constructs a RoleContext + return await self._proxy.update_async( + permission=permission, + ) - :param sid: The unique string that identifies the resource + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :param permission: - :returns: twilio.rest.chat.v1.service.role.RoleContext - :rtype: twilio.rest.chat.v1.service.role.RoleContext + :returns: ApiResponse with instance, status code, and headers """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + permission=permission, + ) - def __call__(self, sid): + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: """ - Constructs a RoleContext + Asynchronous coroutine to update the RoleInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_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) -> tuple: """ - Build an instance of RoleInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.service.role.RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + def delete(self) -> bool: """ - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the RoleInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the RoleInstance and return response metadata -class RoleContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the RoleContext + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :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 + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.service.role.RoleContext - :rtype: twilio.rest.chat.v1.service.role.RoleContext + async def delete_async(self) -> bool: """ - super(RoleContext, self).__init__(version) + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance and return response metadata - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Roles/{sid}'.format(**self._solution) - def fetch(self): + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: """ Fetch the RoleInstance + :returns: The fetched RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + :returns: The fetched RoleInstance + """ + payload, _, _ = await self._fetch_async() return RoleInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the RoleInstance + Asynchronous coroutine to fetch the RoleInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, permission: List[str]) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for update operation - def update(self, permission): + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, permission: List[str]) -> RoleInstance: """ 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._update(permission=permission) + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance and return response metadata + + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, permission: List[str]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Accept"] = "application/json" + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + payload, _, _ = await self._update_async(permission=permission) 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"], + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance and return response metadata + + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 - :returns: twilio.rest.chat.v1.service.role.RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + 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 "" + + +class RoleList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the RoleList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/Roles".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - 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 - :rtype: twilio.rest.chat.v1.service.role.RoleContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: """ - if self._context is None: - self._context = RoleContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the RoleInstance - @property - def sid(self): + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: """ - return self._properties['sid'] + Create the RoleInstance and return response metadata - @property - def account_sid(self): + :param friendly_name: + :param type: + :param permission: + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Account that created the resource - :rtype: unicode + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for create operation - @property - def service_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: """ - return self._properties['service_sid'] + Asynchronously create the RoleInstance - @property - def friendly_name(self): + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: """ - return self._properties['friendly_name'] + Asynchronously create the RoleInstance and return response metadata - @property - def type(self): + :param friendly_name: + :param type: + :param permission: + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The type of role - :rtype: RoleInstance.RoleType + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: """ - return self._properties['type'] + 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 permissions(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 array of the permissions the role has been granted - :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['permissions'] + 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 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 = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_created'] + Streams RoleInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :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_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_updated'] + Asynchronously streams RoleInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The absolute URL of the Role resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: """ - return self._properties['url'] + 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) - def fetch(self): + :returns: list that will contain up to limit results """ - Fetch the RoleInstance - :returns: The fetched RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + return 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._proxy.fetch() + 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) - def delete(self): + :returns: list that will contain up to limit results """ - Deletes the RoleInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.delete() + Lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - def update(self, permission): + :returns: ApiResponse with list of instances, status code, and headers """ - Update the RoleInstance + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoleInstance and returns headers from first page - :param unicode permission: A permission the role should have - :returns: The updated RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.update(permission, ) + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 9bf8647b71..a428c09856 100644 --- a/twilio/rest/ip_messaging/v1/service/user/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/user/__init__.py @@ -1,521 +1,1244 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): - """ """ +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") - def __init__(self, version, service_sid): + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": """ - Initialize the UserList + 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: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v1.service.user.UserList - :rtype: twilio.rest.chat.v1.service.user.UserList + def delete(self) -> bool: """ - super(UserList, self).__init__(version) + Deletes the UserInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Users'.format(**self._solution) - def create(self, identity, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the UserInstance + 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 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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance - :returns: The created UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'Identity': identity, - 'RoleSid': role_sid, - 'Attributes': attributes, - 'FriendlyName': friendly_name, - }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance - :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 await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of UserInstance records from the API. - Request is executed immediately + Fetch the UserInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info - return UserPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of UserInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance - :returns: Page of UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserPage + :param role_sid: + :param attributes: + :param friendly_name: + + :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) + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param role_sid: + :param attributes: + :param friendly_name: - def get(self, sid): + :returns: The updated UserInstance """ - Constructs a UserContext + return await self._proxy.update_async( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return UserContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Constructs a UserContext + Asynchronous coroutine to update the UserInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return UserContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) - def __repr__(self): + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + return self._proxy.user_channels + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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) -> tuple: """ - Build an instance of UserInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.service.user.UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + def delete(self) -> bool: """ - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the UserInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the UserInstance and return response metadata -class UserContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the UserContext + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :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 + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v1.service.user.UserContext - :rtype: twilio.rest.chat.v1.service.user.UserContext + async def delete_async(self) -> bool: """ - super(UserContext, self).__init__(version) + Asynchronous coroutine that deletes the UserInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Users/{sid}'.format(**self._solution) - # Dependents - self._user_channels = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success - def fetch(self): + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: """ Fetch the UserInstance + :returns: The fetched UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() 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_with_http_info_async(self) -> ApiResponse: """ - Deletes the UserInstance + Asynchronous coroutine to fetch the UserInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for update operation - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: """ Update the UserInstance - :param 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._update( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance and return response metadata + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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, + ) -> tuple: + """ + Internal async helper for update operation + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + payload, _, _ = await self._update_async( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) 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"], + ) + + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance and return response metadata + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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'), +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/Users".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + 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, + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: UserContext for this UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - if self._context is None: - self._context = UserContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the UserInstance - @property - def sid(self): + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = self._create( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['sid'] + Create the UserInstance and return response metadata - @property - def account_sid(self): + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Account that created the resource - :rtype: unicode + payload, status_code, headers = self._create( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for create operation - @property - def service_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['service_sid'] + Asynchronously create the UserInstance - @property - def attributes(self): + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance """ - :returns: The JSON string that stores application-specific data - :rtype: unicode + payload, _, _ = await self._create_async( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['attributes'] + Asynchronously create the UserInstance and return response metadata - @property - def friendly_name(self): + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + payload, status_code, headers = await self._create_async( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: """ - return self._properties['friendly_name'] + 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 role_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 assigned to the user - :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[UserInstance]: """ - return self._properties['role_sid'] + 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 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 string that identifies the resource's User - :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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['identity'] + Streams UserInstance and returns headers from first page - @property - def is_online(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: Whether the User is actively connected to the Service instance and online - :rtype: bool + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['is_online'] + Asynchronously streams UserInstance and returns headers from first page - @property - def is_notifiable(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: Whether the User has a potentially valid Push Notification registration for the Service instance - :rtype: bool + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: """ - return self._properties['is_notifiable'] + 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 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[UserInstance]: """ - return self._properties['date_created'] + 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 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 RFC 2822 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Lists UserInstance and returns headers from first page - @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: ApiResponse with list of instances, status code, and headers """ - :returns: The number of Channels this User is a Member of - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['joined_channels_count'] + Asynchronously lists UserInstance and returns headers from first page - @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: ApiResponse with list of instances, status code, and headers """ - :returns: The absolute URLs of the Channel and Binding resources related to the user - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: """ - return self._properties['url'] + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - def fetch(self): + :returns: Page of UserInstance """ - Fetch 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.fetch() + Retrieve a single page with response metadata + - def delete(self): + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers """ - Deletes the UserInstance + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.delete() + Asynchronously retrieve a single page with response metadata - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers """ - Update the UserInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :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 + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: The updated UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> UserPage: """ - return self._proxy.update(role_sid=role_sid, attributes=attributes, friendly_name=friendly_name, ) + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately - @property - def user_channels(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance """ - Access the user_channels + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, solution=self._solution) - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelList + async def get_page_async(self, target_url: str) -> UserPage: """ - return self._proxy.user_channels + 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, solution=self._solution) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 b44fc008f3..28ee7b4930 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,496 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class UserChannelInstance(InstanceResource): + + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOT_PARTICIPATING = "not_participating" + + """ + :ivar account_sid: + :ivar service_sid: + :ivar channel_sid: + :ivar member_sid: + :ivar status: + :ivar last_consumed_message_index: + :ivar unread_messages_count: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], service_sid: str, user_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.member_sid: Optional[str] = payload.get("member_sid") + self.status: Optional["UserChannelInstance.ChannelStatus"] = payload.get( + "status" + ) + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: + """ + Build an instance of UserChannelInstance + + :param payload: Payload response from the API + """ + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class UserChannelList(ListResource): - """ """ - def __init__(self, version, service_sid, user_sid): + def __init__(self, version: Version, service_sid: str, user_sid: str): """ Initialize the UserChannelList - :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 + :param version: Version that contains the resource + :param service_sid: + :param user_sid: - :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) + 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) + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Channels".format( + **self._solution + ) - def stream(self, limit=None, page_size=None): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserChannelInstance]: """ Streams UserChannelInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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.chat.v1.service.user.user_channel.UserChannelInstance] """ 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'], limits['page_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[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. + 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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.chat.v1.service.user.user_channel.UserChannelInstance] """ - 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Retrieve a single page of UserChannelInstance records from the API. - Request is executed immediately + Streams UserChannelInstance and returns headers from first page - :param str page_token: PageToken provided by the API - :param int page_number: 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.v1.service.user.user_channel.UserChannelPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - return UserChannelPage(self._version, response, self._solution) + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - def get_page(self, target_url): + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Retrieve a specific page of UserChannelInstance records from the API. - Request is executed immediately + Asynchronously streams UserChannelInstance and returns headers from first page - :param str target_url: API-generated URL for the requested results page - :returns: Page of UserChannelInstance - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelPage + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] ) - return UserChannelPage(self._version, response, self._solution) + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - def __repr__(self): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: """ - Provide a friendly representation + 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 '' + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) -class UserChannelPage(Page): - """ """ + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Asynchronously lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - def __init__(self, version, response, 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) + + :returns: list that will contain up to limit results """ - 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 unique string that identifies the resource + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelPage - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelPage + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - super(UserChannelPage, self).__init__(version, response) + Lists UserChannelInstance and returns headers from first page - # Path Solution - self._solution = solution - def get_instance(self, payload): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - Build an instance of UserChannelInstance + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserChannelInstance and returns headers from first page + - :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: ApiResponse with list of instances, status code, and headers """ - return UserChannelInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - def __repr__(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, + ) -> UserChannelPage: """ - Provide a friendly representation + Retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately - :returns: Machine friendly representation - :rtype: str + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance """ - return '' + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class UserChannelInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - class ChannelStatus(object): - JOINED = "joined" - INVITED = "invited" - NOT_PARTICIPATING = "not_participating" + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, solution=self._solution) - def __init__(self, version, payload, service_sid, user_sid): + async def 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: """ - Initialize the UserChannelInstance + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance + :param page_token: PageToken provided by the API + :param page_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 """ - super(UserChannelInstance, self).__init__(version) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - # 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'), - } + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'user_sid': user_sid, } + 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'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, solution=self._solution) - @property - def service_sid(self): + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + Retrieve a single page with response metadata - @property - def channel_sid(self): - """ - :returns: The SID of the Channel the resource belongs to - :rtype: unicode - """ - return self._properties['channel_sid'] - @property - def member_sid(self): - """ - :returns: The SID of the User as a Member in the Channel - :rtype: unicode - """ - return self._properties['member_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 status(self): - """ - :returns: The status of the User on the Channel - :rtype: UserChannelInstance.ChannelStatus + :returns: ApiResponse with UserChannelPage, status code, and headers """ - return self._properties['status'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def last_consumed_message_index(self): + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The index of the last Message in the Channel the Member has read - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserChannelPage, status code, and headers """ - return self._properties['last_consumed_message_index'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def unread_messages_count(self): + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> UserChannelPage: """ - :returns: The number of unread Messages in the Channel for the User - :rtype: unicode + 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['unread_messages_count'] + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, solution=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, solution=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 6abddab1a6..7032a6e2f3 100644 --- a/twilio/rest/ip_messaging/v2/credential.py +++ b/twilio/rest/ip_messaging/v2/credential.py @@ -1,431 +1,907 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: + :ivar account_sid: + :ivar friendly_name: + :ivar type: + :ivar sandbox: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } - def __init__(self, version): + self._context: Optional[CredentialContext] = None + + @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 + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v2.credential.CredentialList - :rtype: twilio.rest.chat.v2.credential.CredentialList + def delete(self) -> bool: """ - super(CredentialList, self).__init__(version) + Deletes the CredentialInstance - # Path Solution - self._solution = {} - self._uri = '/Credentials'.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.chat.v2.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.credential.CredentialInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "CredentialInstance": """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + 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 self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance - return CredentialPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched CredentialInstance """ - Retrieve a specific page of CredentialInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info - :returns: Page of CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info - return CredentialPage(self._version, response, self._solution) - 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: ApiResponse with instance, status code, and headers """ - Create the CredentialInstance + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance - :param 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 + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - :returns: The created CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + :returns: The updated CredentialInstance """ - data = values.of({ - 'Type': type, - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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 - return CredentialInstance(self._version, payload, ) + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - def get(self, sid): + :returns: The updated CredentialInstance """ - Constructs a CredentialContext + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - :param sid: The SID of the Credential resource to fetch + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + :returns: ApiResponse with instance, status code, and headers """ - return CredentialContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - def __call__(self, sid): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Constructs a CredentialContext + Asynchronous coroutine to update the CredentialInstance with HTTP info - :param sid: The SID of the Credential resource to fetch + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + :returns: ApiResponse with instance, status code, and headers """ - return CredentialContext(self._version, sid=sid, ) + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialPage(Page): - """ """ +class CredentialContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the CredentialPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the CredentialContext - :returns: twilio.rest.chat.v2.credential.CredentialPage - :rtype: twilio.rest.chat.v2.credential.CredentialPage + :param version: Version that contains the resource + :param sid: """ - super(CredentialPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of CredentialInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v2.credential.CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + def delete(self) -> bool: """ - return CredentialInstance(self._version, payload, ) + Deletes the CredentialInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the CredentialInstance and return response metadata -class CredentialContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the CredentialContext - :param Version version: Version that contains the resource - :param sid: The SID of the Credential resource to fetch + headers = values.of({}) - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(CredentialContext, self).__init__(version) + Asynchronous coroutine that deletes the CredentialInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: """ Fetch the CredentialInstance + :returns: The fetched CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance and return response metadata - 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): + :returns: ApiResponse with instance, status code, and headers """ - Update the CredentialInstance + payload, status_code, headers = self._fetch() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :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 + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: The updated CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ - 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, ) + headers = values.of({}) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CredentialInstance: """ - Deletes the CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched CredentialInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, _, _ = await self._fetch_async() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the CredentialInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + payload, status_code, headers = await self._fetch_async() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + Returns: + tuple: (payload, status_code, headers) + """ -class CredentialInstance(InstanceResource): - """ """ + 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({}) - class PushService(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - def __init__(self, version, payload, sid=None): + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - Initialize the CredentialInstance + Update the CredentialInstance - :returns: twilio.rest.chat.v2.credential.CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance """ - super(CredentialInstance, self).__init__(version) + payload, _, _ = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CredentialInstance and return response metadata - # 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'), - } + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - 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 - :rtype: twilio.rest.chat.v2.credential.CredentialContext + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - if self._context is None: - self._context = CredentialContext(self._version, sid=self._solution['sid'], ) - return self._context + Asynchronous coroutine to update the CredentialInstance - @property - def sid(self): + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['sid'] + Asynchronous coroutine to update the CredentialInstance and return response metadata - @property - def account_sid(self): + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Provide a friendly representation + + :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 friendly_name(self): + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Build an instance of CredentialInstance + + :param payload: Payload response from the API """ - return self._properties['friendly_name'] - @property - def type(self): + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: """ - :returns: The type of push-notification service the credential is for - :rtype: CredentialInstance.PushService + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['type'] + return "" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource - @property - def sandbox(self): """ - :returns: [APN only] Whether to send the credential to sandbox APNs - :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, + ) -> tuple: """ - return self._properties['sandbox'] + Internal helper for create operation - @property - def date_created(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['date_created'] + Create the CredentialInstance - @property - def date_updated(self): + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Create the CredentialInstance and return response metadata - @property - def url(self): + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The absolute URL of the Credential resource - :rtype: unicode + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: """ - return self._properties['url'] + Internal async helper for create operation - def fetch(self): + Returns: + tuple: (payload, status_code, headers) """ - Fetch the CredentialInstance - :returns: The fetched CredentialInstance - :rtype: twilio.rest.chat.v2.credential.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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._proxy.fetch() + Asynchronously create the CredentialInstance - 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 type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance """ - Update the CredentialInstance + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata - :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 type: + :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 + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.update( + payload, status_code, headers = await self._create_async( + type=type, friendly_name=friendly_name, certificate=certificate, private_key=private_key, @@ -433,22 +909,394 @@ def update(self, friendly_name=values.unset, certificate=values.unset, api_key=api_key, secret=secret, ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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. - def delete(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 """ - Deletes the CredentialInstance + limits = self._version.read_limits(limit, page_size) + page = self.page(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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: """ - return self._proxy.delete() + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: + """ + return CredentialContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 d3d62d53a4..a00dfed962 100644 --- a/twilio/rest/ip_messaging/v2/service/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/__init__.py @@ -1,17 +1,25 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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 +27,2027 @@ from twilio.rest.ip_messaging.v2.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 pre_webhook_url: + :ivar post_webhook_url: + :ivar webhook_method: + :ivar webhook_filters: + :ivar pre_webhook_retry_count: + :ivar post_webhook_retry_count: + :ivar notifications: + :ivar media: + :ivar url: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.default_service_role_sid: Optional[str] = payload.get( + "default_service_role_sid" + ) + self.default_channel_role_sid: Optional[str] = payload.get( + "default_channel_role_sid" + ) + self.default_channel_creator_role_sid: Optional[str] = payload.get( + "default_channel_creator_role_sid" + ) + self.read_status_enabled: Optional[bool] = payload.get("read_status_enabled") + self.reachability_enabled: Optional[bool] = payload.get("reachability_enabled") + self.typing_indicator_timeout: Optional[int] = deserialize.integer( + payload.get("typing_indicator_timeout") + ) + self.consumption_report_interval: Optional[int] = deserialize.integer( + payload.get("consumption_report_interval") + ) + self.limits: Optional[Dict[str, object]] = payload.get("limits") + self.pre_webhook_url: Optional[str] = payload.get("pre_webhook_url") + self.post_webhook_url: Optional[str] = payload.get("post_webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.webhook_filters: Optional[List[str]] = payload.get("webhook_filters") + self.pre_webhook_retry_count: Optional[int] = deserialize.integer( + payload.get("pre_webhook_retry_count") + ) + self.post_webhook_retry_count: Optional[int] = deserialize.integer( + payload.get("post_webhook_retry_count") + ) + self.notifications: Optional[Dict[str, object]] = payload.get("notifications") + self.media: Optional[Dict[str, object]] = payload.get("media") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[ServiceContext] = None - 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 + + :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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) - :param Version version: Version that contains the resource + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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.ServiceList - :rtype: twilio.rest.chat.v2.service.ServiceList + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + return self._proxy.bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation """ - super(ServiceList, self).__init__(version) + 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: + """ + super().__init__(version) # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) - def create(self, friendly_name): + self._bindings: Optional[BindingList] = None + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def _delete(self) -> tuple: """ - Create the ServiceInstance + Internal helper for delete operation - :param unicode friendly_name: A string to describe the resource + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: The created ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: + + :returns: The updated ServiceInstance + """ + payload, _, _ = self._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 ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + if self._bindings is None: + self._bindings = BindingList( + self._version, + self._solution["sid"], + ) + return self._bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) + return self._channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + if self._roles is None: + self._roles = RoleList( + self._version, + self._solution["sid"], + ) + return self._roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation """ - data = values.of({'FriendlyName': friendly_name, }) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return ServiceInstance(self._version, payload, ) +class ServicePage(Page): - def stream(self, limit=None, page_size=None): + def get_instance(self, payload: Dict[str, Any]) -> 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Build an instance of ServiceInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.ServiceInstance] + :param payload: Payload response from the API """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits['page_size'], ) + return ServiceInstance(self._version, payload) - return self._version.stream(page, limits['limit'], limits['page_limit']) + def __repr__(self) -> str: + """ + Provide a friendly representation - def list(self, limit=None, page_size=None): + :returns: Machine friendly representation """ - Lists ServiceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return "" - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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] - """ - return list(self.stream(limit=limit, page_size=page_size, )) +class ServiceList(ListResource): - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def __init__(self, version: Version): """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately + Initialize the ServiceList - :param str page_token: PageToken provided by the API - :param 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 - :returns: Page of ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServicePage """ - 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, ) + self._uri = "/Services" - return ServicePage(self._version, response, self._solution) - - def get_page(self, target_url): + def _create(self, friendly_name: str) -> tuple: """ - 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 + Internal helper for create operation - :returns: Page of ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServicePage + Returns: + tuple: (payload, status_code, headers) """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + + data = values.of( + { + "FriendlyName": friendly_name, + } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - return ServicePage(self._version, response, self._solution) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def get(self, sid): + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, friendly_name: str) -> ServiceInstance: """ - Constructs a ServiceContext + Create the ServiceInstance - :param sid: The SID of the Service resource to fetch + :param friendly_name: - :returns: twilio.rest.chat.v2.service.ServiceContext - :rtype: twilio.rest.chat.v2.service.ServiceContext + :returns: The created ServiceInstance """ - return ServiceContext(self._version, sid=sid, ) + payload, _, _ = self._create(friendly_name=friendly_name) + return ServiceInstance(self._version, payload) - def __call__(self, sid): + def create_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Constructs a ServiceContext + Create the ServiceInstance and return response metadata - :param sid: The SID of the Service resource to fetch + :param friendly_name: - :returns: twilio.rest.chat.v2.service.ServiceContext - :rtype: twilio.rest.chat.v2.service.ServiceContext + :returns: ApiResponse with instance, status code, and headers """ - return ServiceContext(self._version, sid=sid, ) + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _create_async(self, friendly_name: str) -> tuple: """ - Provide a friendly representation + Internal async helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class ServicePage(Page): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, response, solution): - """ - Initialize the ServicePage + headers["Accept"] = "application/json" - :param Version version: Version that contains the resource - :param Response response: Response from the API + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.chat.v2.service.ServicePage - :rtype: twilio.rest.chat.v2.service.ServicePage + async def create_async(self, friendly_name: str) -> ServiceInstance: """ - super(ServicePage, self).__init__(version, response) + Asynchronously create the ServiceInstance - # Path Solution - self._solution = solution + :param friendly_name: - def get_instance(self, payload): + :returns: The created ServiceInstance """ - Build an instance of ServiceInstance + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return ServiceInstance(self._version, payload) - :param dict payload: Payload response from the API - - :returns: twilio.rest.chat.v2.service.ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: """ - return ServiceInstance(self._version, payload, ) + Asynchronously create the ServiceInstance and return response metadata - def __repr__(self): - """ - Provide a friendly representation + :param friendly_name: - :returns: Machine friendly representation - :rtype: str + :returns: ApiResponse with instance, status code, and headers """ - return '' + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + 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. -class ServiceContext(InstanceContext): - """ """ + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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, sid): + :returns: Generator that will yield up to limit results """ - Initialize the ServiceContext + 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 sid: The SID of the Service resource to fetch + return self._version.stream(page, limits["limit"]) - :returns: twilio.rest.chat.v2.service.ServiceContext - :rtype: twilio.rest.chat.v2.service.ServiceContext + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: """ - super(ServiceContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) + 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. - # Dependents - self._channels = None - self._roles = None - self._users = None - self._bindings = None + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def fetch(self): + :returns: Generator that will yield up to limit results """ - Fetch the ServiceInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :returns: The fetched ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Streams ServiceInstance and returns headers from first page - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - def delete(self): - """ - Deletes the 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: 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): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - 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 + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - :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'], ) + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - @property - def channels(self): + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Access the channels + Asynchronously streams ServiceInstance and returns headers from first page - :returns: twilio.rest.chat.v2.service.channel.ChannelList - :rtype: twilio.rest.chat.v2.service.channel.ChannelList - """ - if self._channels is None: - self._channels = ChannelList(self._version, service_sid=self._solution['sid'], ) - return self._channels - @property - def roles(self): - """ - Access the roles + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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.role.RoleList - :rtype: twilio.rest.chat.v2.service.role.RoleList + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - if self._roles is None: - self._roles = RoleList(self._version, service_sid=self._solution['sid'], ) - return self._roles + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def users(self): - """ - Access the users + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: twilio.rest.chat.v2.service.user.UserList - :rtype: twilio.rest.chat.v2.service.user.UserList + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: """ - if self._users is None: - self._users = UserList(self._version, service_sid=self._solution['sid'], ) - return self._users + 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 bindings(self): - """ - Access the bindings + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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.v2.service.binding.BindingList - :rtype: twilio.rest.chat.v2.service.binding.BindingList + :returns: list that will contain up to limit results """ - if self._bindings is None: - self._bindings = BindingList(self._version, service_sid=self._solution['sid'], ) - return self._bindings - def __repr__(self): - """ - 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[ServiceInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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) -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'), - } + :returns: list that will contain up to limit results + """ - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def _proxy(self): + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists ServiceInstance and returns headers from first page - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.chat.v2.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 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 account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['account_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def friendly_name(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] + Asynchronously lists ServiceInstance and returns headers from first page - @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'] + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 default_service_role_sid(self): + :returns: ApiResponse with list of instances, status code, and headers """ - :returns: The service role assigned to users when they are added to the service - :rtype: unicode - """ - return self._properties['default_service_role_sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def default_channel_role_sid(self): - """ - :returns: The channel role assigned to users when they are added to a channel - :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, + ) -> ServicePage: """ - return self._properties['default_channel_role_sid'] + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - @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'] + :param page_token: PageToken provided by the 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 read_status_enabled(self): - """ - :returns: Whether the Message Consumption Horizon feature is enabled - :rtype: bool + :returns: Page of ServiceInstance """ - return self._properties['read_status_enabled'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def reachability_enabled(self): - """ - :returns: Whether the Reachability Indicator feature is enabled for this Service instance - :rtype: bool - """ - return self._properties['reachability_enabled'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def typing_indicator_timeout(self): - """ - :returns: How long in seconds to wait before assuming the user is no longer typing - :rtype: unicode - """ - return self._properties['typing_indicator_timeout'] + headers["Accept"] = "application/json" - @property - def consumption_report_interval(self): - """ - :returns: DEPRECATED - :rtype: unicode - """ - return self._properties['consumption_report_interval'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) - @property - def limits(self): + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: """ - :returns: An object that describes the limits of the service instance - :rtype: dict - """ - return self._properties['limits'] + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - @property - def pre_webhook_url(self): - """ - :returns: The webhook URL for pre-event webhooks - :rtype: unicode - """ - return self._properties['pre_webhook_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 post_webhook_url(self): - """ - :returns: The URL for post-event webhooks - :rtype: unicode + :returns: Page of ServiceInstance """ - return self._properties['post_webhook_url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def webhook_method(self): - """ - :returns: The HTTP method to use for both PRE and POST webhooks - :rtype: unicode - """ - return self._properties['webhook_method'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def webhook_filters(self): - """ - :returns: The list of webhook events that are enabled for this Service instance - :rtype: unicode - """ - return self._properties['webhook_filters'] + headers["Accept"] = "application/json" - @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'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) - @property - def post_webhook_retry_count(self): + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The number of times calls to the `post_webhook_url` will be retried - :rtype: unicode - """ - return self._properties['post_webhook_retry_count'] + Retrieve a single page with response metadata - @property - def notifications(self): - """ - :returns: The notification configuration for the Service instance - :rtype: dict - """ - return self._properties['notifications'] - @property - def media(self): - """ - :returns: The properties of the media that the service supports - :rtype: dict - """ - return self._properties['media'] + :param page_token: PageToken provided by the 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: ApiResponse with ServicePage, status code, and headers """ - :returns: The absolute URL of the Service resource - :rtype: unicode - """ - return self._properties['url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def links(self): - """ - :returns: The absolute URLs of the Service's Channels, Roles, and Users - :rtype: unicode - """ - return self._properties['links'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def fetch(self): - """ - Fetch the ServiceInstance + headers["Accept"] = "application/json" - :returns: The fetched ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance - """ - return self._proxy.fetch() + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - def delete(self): + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the ServiceInstance + Asynchronously retrieve a single page with response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - 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): + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers """ - Update the ServiceInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :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 + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: The updated ServiceInstance - :rtype: twilio.rest.chat.v2.service.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, + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def channels(self): + 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 f3eaae9525..b7394ff7a1 100644 --- a/twilio/rest/ip_messaging/v2/service/binding.py +++ b/twilio/rest/ip_messaging/v2/service/binding.py @@ -1,438 +1,873 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +class BindingInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the BindingList + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the Binding resource is associated with + """ + :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") - :returns: twilio.rest.chat.v2.service.binding.BindingList - :rtype: twilio.rest.chat.v2.service.binding.BindingList - """ - super(BindingList, self).__init__(version) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Bindings'.format(**self._solution) + 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'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, binding_type=values.unset, identity=values.unset, limit=None, - page_size=None): + async def delete_async(self) -> bool: """ - Lists BindingInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the BindingInstance - :param BindingInstance.BindingType binding_type: The 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 delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of BindingInstance records from the API. - Request is executed immediately + Deletes the BindingInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - 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, - }) + return self._proxy.delete_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance with HTTP info - return BindingPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with success boolean, status code, and headers """ - Retrieve a specific page of BindingInstance records from the API. - Request is executed immediately + return await self._proxy.delete_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def fetch(self) -> "BindingInstance": + """ + Fetch the BindingInstance - :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 self._proxy.fetch() + + async def fetch_async(self) -> "BindingInstance": + """ + Asynchronous coroutine to fetch the BindingInstance - return BindingPage(self._version, response, self._solution) - def get(self, sid): + :returns: The fetched BindingInstance """ - Constructs a BindingContext + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return BindingContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.fetch_with_http_info() - def __call__(self, sid): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Constructs a BindingContext + Asynchronous coroutine to fetch the BindingInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return BindingContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.fetch_with_http_info_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 BindingPage(Page): - """ """ +class BindingContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the BindingPage - - :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 + Initialize the BindingContext - :returns: twilio.rest.chat.v2.service.binding.BindingPage - :rtype: twilio.rest.chat.v2.service.binding.BindingPage + :param version: Version that contains the resource + :param service_sid: + :param sid: """ - super(BindingPage, 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}/Bindings/{sid}".format(**self._solution) - def get_instance(self, payload): + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of BindingInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.chat.v2.service.binding.BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return BindingInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the BindingInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the BindingInstance and return response metadata -class BindingContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the BindingContext - :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 + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v2.service.binding.BindingContext - :rtype: twilio.rest.chat.v2.service.binding.BindingContext + async def delete_async(self) -> bool: """ - super(BindingContext, self).__init__(version) + Asynchronous coroutine that deletes the BindingInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Bindings/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BindingInstance: """ Fetch the BindingInstance + :returns: The fetched BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the BindingInstance + Asynchronous coroutine to fetch the BindingInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 BindingInstance(InstanceResource): - """ """ +class BindingPage(Page): - class BindingType(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: + """ + Build an instance of BindingInstance - 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'), - } + :param payload: Payload response from the API + """ - # 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 __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: BindingContext for this BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingContext + :returns: Machine friendly representation """ - if self._context is None: - self._context = BindingContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return "" - @property - def sid(self): + +class BindingList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - :returns: The unique string that identifies the resource - :rtype: unicode + Initialize the BindingList + + :param version: Version that contains the resource + :param service_sid: + """ - return self._properties['sid'] + super().__init__(version) - @property - def account_sid(self): + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Bindings".format(**self._solution) + + def stream( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BindingInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['account_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 service_sid(self): + 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]: """ - :returns: The SID of the Service that the Binding resource is associated with - :rtype: unicode + Asynchronously streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['service_sid'] + 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 date_created(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Streams BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) - @property - def date_updated(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Asynchronously streams BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) - @property - def endpoint(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 unique endpoint identifier 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 self._properties['endpoint'] - @property - def identity(self): + 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]: """ - :returns: The string that identifies the resource's User - :rtype: unicode + Asynchronously lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['identity'] + Lists BindingInstance and returns headers from first page - @property - def credential_sid(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: ApiResponse with list of instances, status code, and headers """ - :returns: The SID of the Credential for the binding - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['credential_sid'] + Asynchronously lists BindingInstance and returns headers from first page - @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: ApiResponse with list of instances, status code, and headers """ - :returns: The push technology to use for the binding - :rtype: BindingInstance.BindingType + generator, status_code, headers = await self.stream_with_http_info_async( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['binding_type'] + Retrieve a single page of BindingInstance records from the API. + Request is executed immediately - @property - def message_types(self): + :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 """ - :returns: The Programmable Chat message types the binding is subscribed to - :rtype: unicode + 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, solution=self._solution) + + async def page_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Asynchronously retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param binding_type: + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance """ - 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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with BindingPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with BindingPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 afb9b41d54..5dd5288a73 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/channel/__init__.py @@ -1,17 +1,25 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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 +27,1651 @@ 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, + } - 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): - """ - Create the ChannelInstance + self._context: Optional[ChannelContext] = None - :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 + @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: 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, }) + 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, headers=headers, ) + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ChannelInstance - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - 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( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.ChannelInstance] + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> 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'], ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def list(self, type=values.unset, limit=None, page_size=None): + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - Lists ChannelInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the ChannelInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(type=type, limit=limit, page_size=page_size, )) + return self._proxy.delete_with_http_info( + 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): + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - Retrieve a single page of ChannelInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the ChannelInstance with HTTP info - :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 + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: Page of ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelPage + :returns: ApiResponse with success boolean, status code, and headers """ - 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 ChannelPage(self._version, response, self._solution) + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def get_page(self, target_url): + def fetch(self) -> "ChannelInstance": """ - Retrieve a specific page of ChannelInstance records from the API. - Request is executed immediately + Fetch the ChannelInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelPage + :returns: The fetched ChannelInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ChannelPage(self._version, response, self._solution) + return self._proxy.fetch() - def get(self, sid): + async def fetch_async(self) -> "ChannelInstance": """ - Constructs a ChannelContext + Asynchronous coroutine to fetch the ChannelInstance - :param sid: The SID of the resource - :returns: twilio.rest.chat.v2.service.channel.ChannelContext - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + :returns: The fetched ChannelInstance """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.fetch_async() - def __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a ChannelContext + Fetch the ChannelInstance with HTTP info - :param sid: The SID of the resource - :returns: twilio.rest.chat.v2.service.channel.ChannelContext - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + :returns: ApiResponse with instance, status code, and headers """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.fetch_with_http_info() - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the ChannelInstance with HTTP info - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - return '' + return await self._proxy.fetch_with_http_info_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 -class ChannelPage(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: - def __init__(self, version, response, solution): + :returns: The updated ChannelInstance """ - Initialize the ChannelPage + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) - :param 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 + 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: twilio.rest.chat.v2.service.channel.ChannelPage - :rtype: twilio.rest.chat.v2.service.channel.ChannelPage + :returns: The updated ChannelInstance """ - super(ChannelPage, self).__init__(version, response) + 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, + ) - # Path Solution - self._solution = solution + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ChannelInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) - def get_instance(self, payload): + @property + def invites(self) -> InviteList: """ - Build an instance of ChannelInstance + Access the invites + """ + return self._proxy.invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + return self._proxy.members - :param dict payload: Payload response from the API + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages - :returns: twilio.rest.chat.v2.service.channel.ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks """ - return ChannelInstance(self._version, payload, service_sid=self._solution['service_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 ChannelContext(InstanceContext): - """ """ - def __init__(self, version, service_sid, sid): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the ChannelContext - :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 - - :returns: twilio.rest.chat.v2.service.channel.ChannelContext - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + :param version: Version that contains the resource + :param service_sid: + :param sid: """ - super(ChannelContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Channels/{sid}'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) - # Dependents - self._members = None - self._messages = None - self._invites = None - self._webhooks = None + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None + self._webhooks: Optional[WebhookList] = None - def fetch(self): + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: """ - Fetch the ChannelInstance + Internal helper for delete operation - :returns: The fetched ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) - return ChannelInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers ) - def delete(self, x_twilio_webhook_enabled=values.unset): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ Deletes the ChannelInstance - :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 :returns: True if delete succeeds, False otherwise - :rtype: bool """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success - 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 delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - Update the ChannelInstance + Deletes the ChannelInstance and return response metadata - :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 - :returns: The updated ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + :returns: ApiResponse with success boolean, status code, and 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({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - - 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'], + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return ApiResponse(data=success, status_code=status_code, headers=headers) - @property - def members(self): + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: """ - Access the members + Internal async helper for delete operation - :returns: twilio.rest.chat.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + Returns: + tuple: (success_boolean, status_code, headers) """ - if self._members is None: - self._members = MemberList( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], - ) - return self._members + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) - @property - def messages(self): - """ - Access the messages + headers = values.of({}) - :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'], - ) - return self._messages + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - @property - def invites(self): + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Access the invites + Asynchronous coroutine that deletes the ChannelInstance - :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 + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - @property - def webhooks(self): + :returns: True if delete succeeds, False otherwise """ - Access the webhooks + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return success - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookList - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookList + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - if self._webhooks is None: - self._webhooks = WebhookList( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], - ) - return self._webhooks + Asynchronous coroutine that deletes the ChannelInstance and return response metadata - def __repr__(self): + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers """ - Provide a friendly representation + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) - :returns: Machine friendly representation - :rtype: str + def _fetch(self) -> tuple: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Internal helper for fetch operation + Returns: + tuple: (payload, status_code, headers) + """ -class ChannelInstance(InstanceResource): - """ """ + headers = values.of({}) - class ChannelType(object): - PUBLIC = "public" - PRIVATE = "private" + headers["Accept"] = "application/json" - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - 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'), - } + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): + :returns: The fetched ChannelInstance """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, _, _ = self._fetch() + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - :returns: ChannelContext for this ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + def fetch_with_http_info(self) -> ApiResponse: """ - if self._context is None: - self._context = ChannelContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Fetch the ChannelInstance and return response metadata - @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 + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['account_sid'] + payload, status_code, headers = self._fetch() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def service_sid(self): + async def _fetch_async(self) -> tuple: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + Internal async helper for fetch operation - @property - def friendly_name(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - @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({}) - @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'] + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - @property - def date_created(self): + async def fetch_async(self) -> ChannelInstance: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + Asynchronous coroutine to fetch 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'] - @property - def created_by(self): - """ - :returns: The identity of the User that created the channel - :rtype: unicode + :returns: The fetched ChannelInstance """ - return self._properties['created_by'] + payload, _, _ = await self._fetch_async() + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - @property - def members_count(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: The number of Members in the Channel - :rtype: unicode - """ - return self._properties['members_count'] + Asynchronous coroutine to fetch the ChannelInstance and return response metadata - @property - def messages_count(self): - """ - :returns: The number of Messages that have been passed in the Channel - :rtype: unicode - """ - return self._properties['messages_count'] - @property - def url(self): - """ - :returns: The absolute URL of the Channel resource - :rtype: unicode + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['url'] + payload, status_code, headers = await self._fetch_async() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The updated ChannelInstance + """ + payload, _, _ = self._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 ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def links(self): + def invites(self) -> InviteList: """ - :returns: Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel - :rtype: unicode + Access the invites """ - return self._properties['links'] + if self._invites is None: + self._invites = InviteList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._invites - def fetch(self): + @property + def members(self) -> MemberList: """ - Fetch the ChannelInstance + Access the members + """ + if self._members is None: + self._members = MemberList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._members - :returns: The fetched ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + @property + def messages(self) -> MessageList: """ - return self._proxy.fetch() + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._messages - def delete(self, x_twilio_webhook_enabled=values.unset): + @property + def webhooks(self) -> WebhookList: """ - Deletes the ChannelInstance + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._webhooks - :param ChannelInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Machine friendly representation """ - return self._proxy.delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - 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): + +class ChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: """ - Update the ChannelInstance + Build an instance of 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 payload: Payload response from the API + """ - :returns: The updated ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: """ - return self._proxy.update( + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ChannelList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Channels".format(**self._solution) + + def _create( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The created ChannelInstance + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, friendly_name=friendly_name, unique_name=unique_name, attributes=attributes, + type=type, date_created=date_created, date_updated=date_updated, created_by=created_by, + ) + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def members(self): + def stream( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: """ - Access the members + 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: twilio.rest.chat.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + :returns: Generator that will yield up to limit results """ - return self._proxy.members + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) - @property - def messages(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]: """ - Access the messages + 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: twilio.rest.chat.v2.service.channel.message.MessageList - :rtype: twilio.rest.chat.v2.service.channel.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(type=type, page_size=limits["page_size"]) - @property - def invites(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Access the invites + Streams ChannelInstance and returns headers from first page + + + :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: twilio.rest.chat.v2.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteList + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._proxy.invites + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + type=type, page_size=limits["page_size"] + ) - @property - def webhooks(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Access the webhooks + Asynchronously streams ChannelInstance and returns headers from first page + + + :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: twilio.rest.chat.v2.service.channel.webhook.WebhookList - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookList + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._proxy.webhooks + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + type=type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + type=type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Asynchronously lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChannelInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + type=type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChannelInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + type=type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, solution=self._solution) + + async def page_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ChannelPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ChannelPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ChannelPage: + """ + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ChannelPage: + """ + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 2232efc7e4..3faf373020 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/invite.py +++ b/twilio/rest/ip_messaging/v2/service/channel/invite.py @@ -1,448 +1,985 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 + return self._proxy.delete() - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The Role assigned to the new member + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance - :returns: The created InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + + :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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance with HTTP info - return InviteInstance( - 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: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.invite.InviteInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "InviteInstance": + """ + Fetch the InviteInstance - page = self.page(identity=identity, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched InviteInstance + """ + return self._proxy.fetch() - def list(self, identity=values.unset, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to 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. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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 """ - return list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of InviteInstance records from the API. - Request is executed immediately + Fetch the InviteInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance with HTTP info - return InvitePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of InviteInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InvitePage + :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 InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the InviteContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Invites/{sid}".format( + **self._solution + ) ) - return InvitePage(self._version, response, self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation - def get(self, sid): + Returns: + tuple: (success_boolean, status_code, headers) """ - Constructs a InviteContext - :param sid: The SID of the Invite resource to fetch + headers = values.of({}) - :returns: twilio.rest.chat.v2.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteContext + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return InviteContext( + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + payload, _, _ = self._fetch() + 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 __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a InviteContext + Fetch the InviteInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return InviteContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class InvitePage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> InviteInstance: """ - Initialize the InvitePage + Asynchronous coroutine to fetch the InviteInstance + - :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 + :returns: The fetched InviteInstance + """ + payload, _, _ = await self._fetch_async() + 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 + async def fetch_with_http_info_async(self) -> ApiResponse: """ - super(InvitePage, self).__init__(version, response) + Asynchronous coroutine to fetch the InviteInstance and return response metadata - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of InviteInstance + payload, status_code, headers = await self._fetch_async() + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.chat.v2.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + :returns: Machine friendly representation """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: + """ + Build an instance of InviteInstance + + :param payload: Payload response from the API + """ + return InviteInstance( self._version, payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + 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 + ) -> tuple: """ - Fetch the InviteInstance + Internal helper for create operation - :returns: The fetched InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: + :param role_sid: + + :returns: The created InviteInstance + """ + payload, _, _ = self._create(identity=identity, role_sid=role_sid) 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): + def create_with_http_info( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: """ - Deletes the InviteInstance + Create the InviteInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param identity: + :param role_sid: + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: """ - Provide a friendly representation + Internal async helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - 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"}) -class InviteInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, payload, service_sid, channel_sid, sid=None): + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: """ - Initialize the InviteInstance + Asynchronously create the InviteInstance + + :param identity: + :param role_sid: - :returns: twilio.rest.chat.v2.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + :returns: The created InviteInstance """ - super(InviteInstance, self).__init__(version) + payload, _, _ = await self._create_async(identity=identity, role_sid=role_sid) + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - # 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'), - } + async def create_with_http_info_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the InviteInstance and return response metadata - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + :param identity: + :param role_sid: - @property - def _proxy(self): + :returns: ApiResponse with instance, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, status_code, headers = await self._create_async( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: InviteContext for this InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteContext + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[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 + 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 sid(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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InviteInstance]: """ - return self._properties['sid'] + 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 account_sid(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 """ - :returns: The SID of the Account that created the resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['account_sid'] + Streams InviteInstance and returns headers from first page - @property - def channel_sid(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The SID of the Channel the new resource belongs to - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['channel_sid'] + Asynchronously streams InviteInstance and returns headers from first page - @property - def service_sid(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - return self._properties['service_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. - @property - def identity(self): + :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 """ - :returns: The string that identifies the resource's User - :rtype: unicode + + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - return self._properties['identity'] + 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 date_created(self): + :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 """ - :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( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_created'] + Lists InviteInstance and returns headers from first page - @property - def date_updated(self): + + :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: ApiResponse with list of instances, status code, and headers """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously lists InviteInstance and returns headers from first page - @property - def role_sid(self): + + :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: ApiResponse with list of instances, status code, and headers """ - :returns: The SID of the Role assigned to the member - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['role_sid'] + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately - @property - def created_by(self): + :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 """ - :returns: The identity of the User that created the invite - :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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, solution=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: """ - return self._properties['created_by'] + Asynchronously retrieve a single page of InviteInstance records from the API. + Request is executed immediately - @property - def url(self): + :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 """ - :returns: The absolute URL of the Invite 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 InvitePage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['url'] + Retrieve a single page with response metadata + + + :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 - def fetch(self): + :returns: ApiResponse with InvitePage, status code, and headers """ - Fetch the InviteInstance + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: The fetched InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with InvitePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> InvitePage: """ - return self._proxy.fetch() + Retrieve a specific page of InviteInstance 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 InviteInstance """ - Deletes the InviteInstance + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, solution=self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def get_page_async(self, target_url: str) -> InvitePage: """ - return self._proxy.delete() + Asynchronously retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 907cff7e37..580bbbe1a4 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/member.py +++ b/twilio/rest/ip_messaging/v2/service/channel/member.py @@ -1,563 +1,1630 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class MemberList(ListResource): - """ """ +class MemberInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: + :ivar account_sid: + :ivar channel_sid: + :ivar service_sid: + :ivar identity: + :ivar date_created: + :ivar date_updated: + :ivar role_sid: + :ivar last_consumed_message_index: + :ivar last_consumption_timestamp: + :ivar url: + :ivar attributes: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) + self.url: Optional[str] = payload.get("url") + self.attributes: Optional[str] = payload.get("attributes") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } - def __init__(self, version, service_sid, channel_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 SID 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.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - super(MemberList, self).__init__(version) + Deletes the MemberInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'channel_sid': channel_sid, } - self._uri = '/Services/{service_sid}/Channels/{channel_sid}/Members'.format(**self._solution) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - 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): + :returns: True if delete succeeds, False otherwise """ - Create the MemberInstance + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - :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 + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance - :returns: The created MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - 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, }) + Deletes the MemberInstance with HTTP info - 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: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) - def stream(self, identity=values.unset, limit=None, page_size=None): + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - 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. + Asynchronous coroutine that deletes the MemberInstance with HTTP info - :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) + :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.member.MemberInstance] + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - page = self.page(identity=identity, page_size=limits['page_size'], ) + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, identity=values.unset, limit=None, page_size=None): + :returns: The fetched MemberInstance """ - Lists MemberInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return 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. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.member.MemberInstance] + + :returns: The fetched MemberInstance """ - return list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of MemberInstance records from the API. - Request is executed immediately + Fetch the MemberInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance with HTTP info - return MemberPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of MemberInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance - :returns: Page of MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberPage + :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 """ - 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, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, ) - return MemberPage(self._version, response, self._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: - def get(self, sid): + :returns: The updated MemberInstance """ - Constructs a MemberContext + 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, + ) - :param sid: The SID of the Member resource to fetch + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the MemberInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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, + ) - :returns: twilio.rest.chat.v2.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext - """ - return MemberContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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 __call__(self, sid): + def __repr__(self) -> str: """ - Constructs a MemberContext + Provide a friendly representation - :param sid: The SID of the Member resource to fetch + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MemberContext(InstanceContext): - :returns: twilio.rest.chat.v2.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - return MemberContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + Initialize the MemberContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Members/{sid}".format( + **self._solution + ) ) - def __repr__(self): + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: """ - Provide a friendly representation + Internal helper for delete operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (success_boolean, status_code, headers) """ - return '' + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + headers = values.of({}) -class MemberPage(Page): - """ """ + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Initialize the MemberPage + Deletes 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 SID of the Channel for the member + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.chat.v2.service.channel.member.MemberPage - :rtype: twilio.rest.chat.v2.service.channel.member.MemberPage + :returns: True if delete succeeds, False otherwise """ - super(MemberPage, self).__init__(version, response) + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success - # Path Solution - self._solution = solution + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MemberInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def get_instance(self, payload): + :returns: ApiResponse with success boolean, status code, and headers """ - Build an instance of MemberInstance + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation - :returns: twilio.rest.chat.v2.service.channel.member.MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - return MemberInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } ) - def __repr__(self): + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the MemberInstance - :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 '' + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return success + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance and return response metadata -class MemberContext(InstanceContext): - """ """ + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def __init__(self, version, service_sid, channel_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the MemberContext + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, 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 member belongs to - :param sid: The SID of the Member resource to fetch + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.chat.v2.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext + Returns: + tuple: (payload, status_code, headers) """ - super(MemberContext, 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}/Members/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: """ Fetch the MemberInstance + :returns: The fetched MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + :returns: The fetched MemberInstance + """ + payload, _, _ = await self._fetch_async() 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"], + sid=self._solution["sid"], ) - def delete(self, x_twilio_webhook_enabled=values.unset): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the MemberInstance + Asynchronous coroutine to fetch the MemberInstance and return response metadata - :param MemberInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: ApiResponse with instance, status code, and headers """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + payload, status_code, headers = await self._fetch_async() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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({}) - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + 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" - 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): + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 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 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 - :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._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, + ) + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the MemberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) 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"], + sid=self._solution["sid"], ) - def __repr__(self): + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide 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 MemberInstance(InstanceResource): - """ """ +class MemberPage(Page): - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: + """ + Build an instance of MemberInstance - 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'), - } + :param payload: Payload response from the API + """ + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - # Context - self._context = None + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MemberList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MemberList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "channel_sid": channel_sid, } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + def _create( + self, + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, 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", + } + ) - :returns: MemberContext for this MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - 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 + Create the MemberInstance - @property - def sid(self): + :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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = self._create( + identity=identity, + 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, + ) + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the MemberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + 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, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, 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", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronously create the MemberInstance + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The created MemberInstance """ - return self._properties['sid'] + payload, _, _ = await self._create_async( + identity=identity, + 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, + ) + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def account_sid(self): + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the MemberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + 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, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) - @property - def channel_sid(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: """ - :returns: The SID of the Channel for the member - :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 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 """ - return self._properties['channel_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) - @property - def service_sid(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + Streams MemberInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['service_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) - @property - def identity(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The string that identifies the resource's User - :rtype: unicode + Asynchronously streams MemberInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['identity'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) - @property - def date_created(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :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 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 self._properties['date_created'] - @property - def date_updated(self): + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Asynchronously lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['date_updated'] - @property - def role_sid(self): + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Role assigned to the member - :rtype: unicode + Lists MemberInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers """ - return self._properties['role_sid'] + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def last_consumed_message_index(self): + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The index of the last Message that the Member has read within the Channel - :rtype: unicode + Asynchronously lists MemberInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers """ - return self._properties['last_consumed_message_index'] + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def last_consumption_timestamp(self): + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: """ - :returns: The ISO 8601 based timestamp string that represents the datetime of the last Message read event for the Member within the Channel - :rtype: datetime + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance """ - return self._properties['last_consumption_timestamp'] + data = values.of( + { + "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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, solution=self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: """ - :returns: The absolute URL of the Member resource - :rtype: unicode + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance """ - 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): + headers = values.of({"Content-Type": "application/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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: """ - :returns: The JSON string that stores application-specific data - :rtype: unicode + Retrieve a single page with response metadata + + + :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: ApiResponse with MemberPage, status code, and headers """ - return self._properties['attributes'] + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with MemberPage, status code, and headers + """ + 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"}) - def fetch(self): + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 sid: + """ + 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 - :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 + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext - :returns: The updated MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + :param sid: """ - return self._proxy.update( - role_sid=role_sid, - last_consumed_message_index=last_consumed_message_index, - last_consumption_timestamp=last_consumption_timestamp, - date_created=date_created, - date_updated=date_updated, - attributes=attributes, - x_twilio_webhook_enabled=x_twilio_webhook_enabled, + 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 df9803e228..f53ed8a70b 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/message.py +++ b/twilio/rest/ip_messaging/v2/service/channel/message.py @@ -1,600 +1,1630 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class MessageList(ListResource): - """ """ +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: + :ivar account_sid: + :ivar attributes: + :ivar service_sid: + :ivar to: + :ivar channel_sid: + :ivar date_created: + :ivar date_updated: + :ivar last_updated_by: + :ivar was_edited: + :ivar _from: + :ivar body: + :ivar index: + :ivar type: + :ivar media: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.service_sid: Optional[str] = payload.get("service_sid") + self.to: Optional[str] = payload.get("to") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.last_updated_by: Optional[str] = payload.get("last_updated_by") + self.was_edited: Optional[bool] = payload.get("was_edited") + self._from: Optional[str] = payload.get("from") + self.body: Optional[str] = payload.get("body") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.type: Optional[str] = payload.get("type") + self.media: Optional[Dict[str, object]] = payload.get("media") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } - def __init__(self, version, service_sid, channel_sid): + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": """ - Initialize the MessageList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel the Message resource belongs to + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v2.service.channel.message.MessageList - :rtype: twilio.rest.chat.v2.service.channel.message.MessageList + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - super(MessageList, self).__init__(version) + Deletes the MessageInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'channel_sid': channel_sid, } - self._uri = '/Services/{service_sid}/Channels/{channel_sid}/Messages'.format(**self._solution) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - 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): + :returns: True if delete succeeds, False otherwise """ - Create the MessageInstance + 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 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 + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: The created MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - 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 with HTTP info - 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: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) - def stream(self, order=values.unset, limit=None, page_size=None): + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: """ - 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 with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - page = self.page(order=order, page_size=limits['page_size'], ) + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, order=values.unset, limit=None, page_size=None): + :returns: The fetched MessageInstance """ - Lists MessageInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return self._proxy.fetch() - :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) + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately + Fetch the MessageInstance with HTTP info - :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: """ - data = values.of({ - 'Order': order, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Asynchronous coroutine to fetch the MessageInstance with HTTP info - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return MessagePage(self._version, response, self._solution) + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() - def get_page(self, target_url): + 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": """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately + Update the MessageInstance - :param str target_url: API-generated URL for the requested results page + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :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 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_, ) - return MessagePage(self._version, response, self._solution) + 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_: - def get(self, sid): + :returns: The updated MessageInstance """ - Constructs a MessageContext + 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_, + ) - :param sid: The SID of the Message resource to fetch + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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_, + ) - :returns: twilio.rest.chat.v2.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext - """ - return MessageContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, ) - def __call__(self, sid): + def __repr__(self) -> str: """ - Constructs a MessageContext + Provide a friendly representation - :param sid: The SID of the Message resource to fetch + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +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 __repr__(self): + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: """ - Provide a friendly representation + Internal helper for delete operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (success_boolean, status_code, headers) """ - return '' + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + headers = values.of({}) -class MessagePage(Page): - """ """ + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Initialize the MessagePage + 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 SID of the Channel the Message resource belongs to + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.chat.v2.service.channel.message.MessagePage - :rtype: twilio.rest.chat.v2.service.channel.message.MessagePage + :returns: True if delete succeeds, False otherwise """ - super(MessagePage, self).__init__(version, response) + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success - # Path Solution - self._solution = solution + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def get_instance(self, payload): + :returns: ApiResponse with success boolean, status code, and headers """ - Build an instance of MessageInstance + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation - :returns: twilio.rest.chat.v2.service.channel.message.MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - return MessageInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } ) - def __repr__(self): + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 '' + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return success + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance and return response metadata -class MessageContext(InstanceContext): - """ """ + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def __init__(self, version, service_sid, channel_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the MessageContext + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, 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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.chat.v2.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext + Returns: + tuple: (payload, status_code, headers) """ - 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) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> 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, ) - + payload, _, _ = self._fetch() 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Deletes the MessageInstance + Fetch the MessageInstance and return response metadata - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: ApiResponse with instance, status code, and headers """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + payload, status_code, headers = self._fetch() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - 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): + Returns: + tuple: (payload, status_code, headers) """ - 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 - :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 + headers = values.of({}) - :returns: The updated MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> MessageInstance: """ - data = values.of({ - 'Body': body, - 'Attributes': attributes, - 'DateCreated': serialize.iso8601_datetime(date_created), - 'DateUpdated': serialize.iso8601_datetime(date_updated), - 'LastUpdatedBy': last_updated_by, - 'From': from_, - }) - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + Asynchronous coroutine to fetch the MessageInstance - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + :returns: The fetched MessageInstance + """ + payload, _, _ = await self._fetch_async() 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 __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the MessageInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + payload, status_code, headers = await self._fetch_async() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 -class MessageInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - class OrderType(object): - ASC = "asc" - DESC = "desc" + headers["Accept"] = "application/json" - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - 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'), - } + 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 - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: - @property - def _proxy(self): + :returns: The updated MessageInstance """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, _, _ = self._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_, + ) + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) - :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'], + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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_, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 ) - return self._context + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled - @property - def sid(self): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = await self._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 MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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_, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - 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 + 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: """ - return self._properties['account_sid'] + Build an instance of MessageInstance - @property - def attributes(self): + :param payload: Payload response from the API """ - :returns: The JSON string that stores application-specific data - :rtype: unicode + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: """ - return self._properties['attributes'] + Provide a friendly representation - @property - def service_sid(self): + :returns: Machine friendly representation """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + return "" + + +class MessageList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - return self._properties['service_sid'] + Initialize the MessageList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: - @property - def to(self): """ - :returns: The SID of the Channel that the message was sent to - :rtype: unicode + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) + + def _create( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "From": from_, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "Body": body, + "MediaSid": media_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._properties['to'] + Create the MessageInstance - @property - def channel_sid(self): + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param body: + :param media_sid: + + :returns: The created MessageInstance """ - :returns: The SID of the Channel the Message resource belongs to - :rtype: unicode + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param body: + :param media_sid: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "From": from_, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "Body": body, + "MediaSid": media_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param body: + :param media_sid: + + :returns: The created MessageInstance """ - return self._properties['channel_sid'] + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def date_created(self): + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param body: + :param media_sid: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :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(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['date_created'] + 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 date_updated(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 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(order=order, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_updated'] + Streams MessageInstance and returns headers from first page - @property - def last_updated_by(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The Identity of the User who last updated the Message - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['last_updated_by'] + Asynchronously streams MessageInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: Whether the message has been edited since it was created - :rtype: bool + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - return self._properties['was_edited'] + 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 from_(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 """ - :returns: The Identity of the message's author - :rtype: unicode + + 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['from_'] + 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 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 """ - :returns: The content of the message - :rtype: unicode + + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['body'] + Lists MessageInstance and returns headers from first page - @property - def index(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: ApiResponse with list of instances, status code, and headers """ - :returns: The index of the message within the Channel - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + order=order, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['index'] + Asynchronously lists MessageInstance and returns headers from first page - @property - def type(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: ApiResponse with list of instances, status code, and headers """ - :returns: The Message type - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['type'] + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately - @property - def media(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 + """ + 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, solution=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: A Media object that describes the Message's media if attached; otherwise, null - :rtype: dict + 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['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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: """ - :returns: The absolute URL of the Message resource - :rtype: unicode + Retrieve a single page with response metadata + + + :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: ApiResponse with MessagePage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "Order": order, + "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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 fe1baaf441..a72375bb7a 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/webhook.py +++ b/twilio/rest/ip_messaging/v2/service/channel/webhook.py @@ -1,524 +1,1417 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance with HTTP info - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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.webhook.WebhookInstance] + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "WebhookInstance": """ - Retrieve a single page of WebhookInstance records from the API. - Request is executed immediately + 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.chat.v2.service.channel.webhook.WebhookPage + :returns: The fetched WebhookInstance """ - 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) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance - return WebhookPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched WebhookInstance """ - Retrieve a specific page of WebhookInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookPage + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info - return WebhookPage(self._version, response, self._solution) - 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: ApiResponse with instance, status code, and headers """ - Create the WebhookInstance + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance - :param 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 + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: - :returns: The created WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + :returns: The updated WebhookInstance """ - data = values.of({ - 'Type': type, - 'Configuration.Url': configuration_url, - 'Configuration.Method': configuration_method, - 'Configuration.Filters': serialize.map(configuration_filters, lambda e: e), - 'Configuration.Triggers': serialize.map(configuration_triggers, lambda e: e), - 'Configuration.FlowSid': configuration_flow_sid, - 'Configuration.RetryCount': configuration_retry_count, - }) + 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, + ) - payload = self._version.create(method='POST', uri=self._uri, data=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 WebhookInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + :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(self, sid): + def update_with_http_info( + 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, + ) -> ApiResponse: """ - Constructs a WebhookContext + Update the WebhookInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WebhookContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + return self._proxy.update_with_http_info( + 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 __call__(self, sid): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Constructs a WebhookContext + Asynchronous coroutine to update the WebhookInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WebhookContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + return await self._proxy.update_with_http_info_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, ) - def __repr__(self): + 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): - """ """ +class WebhookContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - Initialize the WebhookPage - - :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 + Initialize the WebhookContext - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookPage - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookPage + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: """ - super(WebhookPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Webhooks/{sid}".format( + **self._solution + ) + ) - def get_instance(self, payload): + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of WebhookInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return WebhookInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + 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 '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance and return response metadata -class WebhookContext(InstanceContext): - """ """ - def __init__(self, version, service_sid, channel_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the WebhookContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookContext - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookContext + Returns: + tuple: (payload, status_code, headers) """ - super(WebhookContext, 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}/Webhooks/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: """ Fetch the WebhookInstance + :returns: The fetched WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() 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"], + 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, - configuration_retry_count=values.unset): + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: """ Update the WebhookInstance - :param 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 + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: :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, - }) + payload, _, _ = self._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 WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the WebhookInstance and return response metadata + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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({}) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The updated WebhookInstance + """ + payload, _, _ = await self._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, + ) 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"], + sid=self._solution["sid"], ) - def delete(self): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Deletes the WebhookInstance + Asynchronous coroutine to update the WebhookInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._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, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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): - """ """ +class WebhookPage(Page): - class Type(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 + """ - def __init__(self, version, payload, service_sid, channel_sid, sid=None): + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: """ - Initialize the WebhookInstance + Provide a friendly representation - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.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'), - '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')), - } - # Context - self._context = None +class WebhookList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "channel_sid": channel_sid, } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Webhooks".format( + **self._solution + ) - @property - def _proxy(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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - 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 WebhookInstance - :returns: WebhookContext for this WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookContext + :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 """ - 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 + payload, _, _ = self._create( + type=type, + 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 WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def sid(self): + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the WebhookInstance and return response metadata + + :param type: + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + 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, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = await self._create_async( + type=type, + 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 WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the WebhookInstance and return response metadata + + :param type: + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + 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, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebhookInstance]: """ - return self._properties['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 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[WebhookInstance]: """ - return self._properties['account_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 service_sid(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Service that the Channel Webhook resource is associated with - :rtype: unicode + Streams WebhookInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['service_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def channel_sid(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Channel the Channel Webhook resource belongs to - :rtype: unicode + Asynchronously streams WebhookInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['channel_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def type(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: """ - :returns: The type of 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['type'] - @property - def url(self): + return 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]: """ - :returns: The absolute URL of the Channel Webhook resource - :rtype: unicode + 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['url'] - @property - def configuration(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The JSON string that describes the configuration object for the channel webhook - :rtype: dict + Lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['configuration'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def date_created(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Asynchronously lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_created'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> WebhookPage: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :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_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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, solution=self._solution) + + async def 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: """ - Fetch the WebhookInstance + Asynchronously retrieve a single page of WebhookInstance records from the API. + Request is executed immediately - :returns: The fetched WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + :param page_token: PageToken provided by the API + :param page_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._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 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): + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Update the WebhookInstance + Retrieve a single page with response metadata - :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 - :returns: The updated WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers """ - 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, + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - def delete(self): + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the WebhookInstance + Asynchronously retrieve a single page with response metadata - :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: ApiResponse with WebhookPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: + """ + return WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: + """ + return WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 3158100cc0..02f3e055e0 100644 --- a/twilio/rest/ip_messaging/v2/service/role.py +++ b/twilio/rest/ip_messaging/v2/service/role.py @@ -1,442 +1,1086 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class RoleList(ListResource): - """ """ +class RoleInstance(InstanceResource): + + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar friendly_name: + :ivar type: + :ivar permissions: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } - def __init__(self, version, service_sid): + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": """ - Initialize the RoleList + 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: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v2.service.role.RoleList - :rtype: twilio.rest.chat.v2.service.role.RoleList + def delete(self) -> bool: """ - super(RoleList, self).__init__(version) + Deletes the RoleInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Roles'.format(**self._solution) - def create(self, friendly_name, type, permission): + :returns: True if delete succeeds, False otherwise """ - Create the RoleInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance - :returns: The created RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Type': type, - 'Permission': serialize.map(permission, lambda e: e), - }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.role.RoleInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.role.RoleInstance] + + :returns: The fetched RoleInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of RoleInstance records from the API. - Request is executed immediately + Fetch the RoleInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info - return RolePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of RoleInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance - :param str target_url: API-generated URL for the requested results page + :param permission: - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RolePage + :returns: The updated RoleInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + permission=permission, ) - return RolePage(self._version, response, self._solution) + async def update_async(self, permission: List[str]) -> "RoleInstance": + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: - def get(self, sid): + :returns: The updated RoleInstance """ - Constructs a RoleContext + return await self._proxy.update_async( + permission=permission, + ) - :param sid: The SID of the Role resource to fetch + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :param permission: - :returns: twilio.rest.chat.v2.service.role.RoleContext - :rtype: twilio.rest.chat.v2.service.role.RoleContext + :returns: ApiResponse with instance, status code, and headers """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + permission=permission, + ) - def __call__(self, sid): + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: """ - Constructs a RoleContext + Asynchronous coroutine to update the RoleInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_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) -> tuple: """ - Build an instance of RoleInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v2.service.role.RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + def delete(self) -> bool: """ - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the RoleInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the RoleInstance and return response metadata -class RoleContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the RoleContext + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :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 + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v2.service.role.RoleContext - :rtype: twilio.rest.chat.v2.service.role.RoleContext + async def delete_async(self) -> bool: """ - super(RoleContext, self).__init__(version) + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance and return response metadata - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Roles/{sid}'.format(**self._solution) - def fetch(self): + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: """ Fetch the RoleInstance + :returns: The fetched RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + :returns: The fetched RoleInstance + """ + payload, _, _ = await self._fetch_async() return RoleInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the RoleInstance + Asynchronous coroutine to fetch the RoleInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, permission: List[str]) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for update operation - def update(self, permission): + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, permission: List[str]) -> RoleInstance: """ 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._update(permission=permission) + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance and return response metadata + + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, permission: List[str]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Accept"] = "application/json" + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + payload, _, _ = await self._update_async(permission=permission) 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"], + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance and return response metadata + + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 - :returns: twilio.rest.chat.v2.service.role.RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + 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 "" + + +class RoleList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the RoleList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/Roles".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - 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 - :rtype: twilio.rest.chat.v2.service.role.RoleContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: """ - if self._context is None: - self._context = RoleContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the RoleInstance - @property - def sid(self): + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: """ - return self._properties['sid'] + Create the RoleInstance and return response metadata - @property - def account_sid(self): + :param friendly_name: + :param type: + :param permission: + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Account that created the resource - :rtype: unicode + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for create operation - @property - def service_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: """ - return self._properties['service_sid'] + Asynchronously create the RoleInstance - @property - def friendly_name(self): + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: """ - return self._properties['friendly_name'] + Asynchronously create the RoleInstance and return response metadata - @property - def type(self): + :param friendly_name: + :param type: + :param permission: + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The type of role - :rtype: RoleInstance.RoleType + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: """ - return self._properties['type'] + 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 permissions(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 array of the permissions the role has been granted - :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['permissions'] + 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_created'] + Streams RoleInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :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_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_updated'] + Asynchronously streams RoleInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The absolute URL of the Role resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: """ - return self._properties['url'] + 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) - def fetch(self): + :returns: list that will contain up to limit results """ - Fetch the RoleInstance - :returns: The fetched RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + return 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._proxy.fetch() + 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) - def delete(self): + :returns: list that will contain up to limit results """ - Deletes the RoleInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.delete() + Lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - def update(self, permission): + :returns: ApiResponse with list of instances, status code, and headers """ - Update the RoleInstance + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoleInstance and returns headers from first page - :param unicode permission: A permission the role should have - :returns: The updated RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.update(permission, ) + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 b8f47c5300..b6eb03d7f4 100644 --- a/twilio/rest/ip_messaging/v2/service/user/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/user/__init__.py @@ -1,563 +1,1379 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page from twilio.rest.ip_messaging.v2.service.user.user_binding import UserBindingList from twilio.rest.ip_messaging.v2.service.user.user_channel import UserChannelList -class UserList(ListResource): - """ """ +class UserInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar attributes: + :ivar friendly_name: + :ivar role_sid: + :ivar identity: + :ivar is_online: + :ivar is_notifiable: + :ivar date_created: + :ivar date_updated: + :ivar joined_channels_count: + :ivar links: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.role_sid: Optional[str] = payload.get("role_sid") + self.identity: Optional[str] = payload.get("identity") + self.is_online: Optional[bool] = payload.get("is_online") + self.is_notifiable: Optional[bool] = payload.get("is_notifiable") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.joined_channels_count: Optional[int] = deserialize.integer( + payload.get("joined_channels_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[UserContext] = None - def __init__(self, version, service_sid): + @property + def _proxy(self) -> "UserContext": """ - Initialize the UserList + 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: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.chat.v2.service.user.UserList - :rtype: twilio.rest.chat.v2.service.user.UserList + def delete(self) -> bool: """ - super(UserList, self).__init__(version) + Deletes the UserInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Users'.format(**self._solution) - def create(self, identity, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset, x_twilio_webhook_enabled=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the UserInstance + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes 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 - :returns: The created UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'Identity': identity, - 'RoleSid': role_sid, - 'Attributes': attributes, - 'FriendlyName': friendly_name, - }) - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.UserInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance - :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 await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of UserInstance records from the API. - Request is executed immediately + Fetch the UserInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info - return UserPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of UserInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance - :param str target_url: API-generated URL for the requested results page + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: - :returns: Page of UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserPage + :returns: The updated UserInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, ) - return UserPage(self._version, response, self._solution) + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: - def get(self, sid): + :returns: The updated UserInstance """ - Constructs a UserContext + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) - :param sid: The SID of the User resource to fetch + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers """ - return UserContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Constructs a UserContext + Asynchronous coroutine to update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) - :param sid: The SID of the User resource to fetch + @property + def user_bindings(self) -> UserBindingList: + """ + 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 + 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_bindings: Optional[UserBindingList] = None + self._user_channels: Optional[UserChannelList] = None + + def _delete(self) -> tuple: """ - Build an instance of UserInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :returns: twilio.rest.chat.v2.service.user.UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the UserInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the UserInstance and return response metadata -class UserContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the UserContext - :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 + headers = values.of({}) - :returns: twilio.rest.chat.v2.service.user.UserContext - :rtype: twilio.rest.chat.v2.service.user.UserContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(UserContext, self).__init__(version) + Asynchronous coroutine that deletes the UserInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Users/{sid}'.format(**self._solution) - # Dependents - self._user_channels = None - self._user_bindings = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", 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, ) + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() 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_with_http_info_async(self) -> ApiResponse: """ - Deletes the UserInstance + Asynchronous coroutine to fetch the UserInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, 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 - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset, x_twilio_webhook_enabled=values.unset): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + :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 + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) 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_with_http_info_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, + ) -> ApiResponse: """ - Access the user_channels + Asynchronous coroutine to update the UserInstance and return response metadata - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelList + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers """ - if self._user_channels is None: - self._user_channels = UserChannelList( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['sid'], - ) - return self._user_channels + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 UserPage(Page): - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance - 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'), - } + :param payload: Payload response from the API + """ - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + return UserInstance( + 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: UserContext for this UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserContext + :returns: Machine friendly representation """ - if self._context is None: - self._context = UserContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return "" - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + +class UserList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - return self._properties['sid'] + Initialize the UserList + + :param version: Version that contains the resource + :param service_sid: - @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}/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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['account_sid'] + Create the UserInstance - @property - def service_sid(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: The SID of the Service that the resource is associated with - :rtype: unicode + payload, _, _ = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the UserInstance and return response metadata + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['service_sid'] + payload, _, _ = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def attributes(self): + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the UserInstance and return response metadata + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: """ - :returns: The JSON string that stores application-specific data - :rtype: unicode + 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['attributes'] + 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[UserInstance]: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + 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['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def role_sid(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Role assigned to the user - :rtype: unicode + Streams UserInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['role_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def identity(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The string that identifies the resource's User - :rtype: unicode + Asynchronously streams UserInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['identity'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def is_online(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: """ - :returns: Whether the User is actively connected to the Service instance and online - :rtype: bool + 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['is_online'] - @property - def is_notifiable(self): + return 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]: """ - :returns: Whether the User has a potentially valid Push Notification registration for the Service instance - :rtype: bool + 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['is_notifiable'] - @property - def date_created(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_created'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def date_updated(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Asynchronously lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_updated'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def joined_channels_count(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 number of Channels the User is a Member of - :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['joined_channels_count'] + 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 UserPage(self._version, response, solution=self._solution) + + async def 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: """ - :returns: The absolute URLs of the Channel and Binding resources related to the user - :rtype: unicode + 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 """ - return self._properties['links'] + 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 UserPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The absolute URL of the User resource - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers """ - return self._properties['url'] + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Fetch the UserInstance + Asynchronously retrieve a single page with response metadata - :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: ApiResponse with UserPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - 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, solution=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, solution=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 c29a6b402a..cf7b3f7fc9 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,887 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +class UserBindingInstance(InstanceResource): + + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" - def __init__(self, version, service_sid, user_sid): + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar date_created: + :ivar date_updated: + :ivar endpoint: + :ivar identity: + :ivar user_sid: + :ivar credential_sid: + :ivar binding_type: + :ivar message_types: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + user_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.endpoint: Optional[str] = payload.get("endpoint") + self.identity: Optional[str] = payload.get("identity") + self.user_sid: Optional[str] = payload.get("user_sid") + self.credential_sid: Optional[str] = payload.get("credential_sid") + self.binding_type: Optional["UserBindingInstance.BindingType"] = payload.get( + "binding_type" + ) + self.message_types: Optional[List[str]] = payload.get("message_types") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "sid": sid or self.sid, + } + + self._context: Optional[UserBindingContext] = None + + @property + def _proxy(self) -> "UserBindingContext": """ - Initialize the UserBindingList + 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 user_sid: The SID of the User with the binding + :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: twilio.rest.chat.v2.service.user.user_binding.UserBindingList - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingList + def delete(self) -> bool: """ - super(UserBindingList, self).__init__(version) + Deletes the UserBindingInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'user_sid': user_sid, } - self._uri = '/Services/{service_sid}/Users/{user_sid}/Bindings'.format(**self._solution) - def stream(self, binding_type=values.unset, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return self._proxy.delete() - :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) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserBindingInstance - :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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(binding_type=binding_type, page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserBindingInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, binding_type=values.unset, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists UserBindingInstance 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.delete_with_http_info() - :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) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserBindingInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(binding_type=binding_type, limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_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 + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserBindingInstance": """ - data = values.of({ - 'BindingType': serialize.map(binding_type, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Asynchronous coroutine to fetch the UserBindingInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return UserBindingPage(self._version, response, self._solution) + :returns: The fetched UserBindingInstance + """ + return await self._proxy.fetch_async() - def get_page(self, target_url): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a specific page of UserBindingInstance records from the API. - Request is executed immediately + Fetch the UserBindingInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingPage + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserBindingInstance with HTTP info - return UserBindingPage(self._version, response, self._solution) - def get(self, sid): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a UserBindingContext + return await self._proxy.fetch_with_http_info_async() - :param sid: The SID of the User Binding resource to fetch + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext + :returns: Machine friendly representation """ - return UserBindingContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - sid=sid, + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserBindingContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, user_sid: str, sid: str): + """ + Initialize the UserBindingContext + + :param version: Version that contains the resource + :param service_sid: + :param user_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Bindings/{sid}".format( + **self._solution ) - def __call__(self, sid): + def _delete(self) -> tuple: """ - Constructs a UserBindingContext + Internal helper for delete operation - :param sid: The SID of the User Binding resource to fetch + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return UserBindingContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - sid=sid, + Deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserBindingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + 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 '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserBindingInstance and return response metadata -class UserBindingPage(Page): - """ """ - def __init__(self, version, response, solution): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the UserBindingPage + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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 user_sid: The SID of the User with the binding + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingPage - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingPage + Returns: + tuple: (payload, status_code, headers) """ - super(UserBindingPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) + + headers["Accept"] = "application/json" - def get_instance(self, payload): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserBindingInstance: """ - Build an instance of UserBindingInstance + Fetch the UserBindingInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance + :returns: The fetched UserBindingInstance """ + payload, _, _ = self._fetch() 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Fetch the UserBindingInstance and return response metadata - :returns: Machine friendly representation - :rtype: str - """ - return '' + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) -class UserBindingContext(InstanceContext): - """ """ + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - def __init__(self, version, service_sid, user_sid, sid): + Returns: + tuple: (payload, status_code, headers) """ - Initialize the UserBindingContext - :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 + headers = values.of({}) - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - """ - super(UserBindingContext, self).__init__(version) + headers["Accept"] = "application/json" - # 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) + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + async def fetch_async(self) -> UserBindingInstance: """ - Fetch the UserBindingInstance + Asynchronous coroutine to fetch the UserBindingInstance + :returns: The fetched UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - + payload, _, _ = await self._fetch_async() 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"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the UserBindingInstance + Asynchronous coroutine to fetch the UserBindingInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 UserBindingInstance(InstanceResource): - """ """ +class UserBindingPage(Page): - class BindingType(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + def get_instance(self, payload: Dict[str, Any]) -> UserBindingInstance: + """ + Build an instance of UserBindingInstance - 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 payload: Payload response from the API + """ - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'user_sid': user_sid, - 'sid': sid or self._properties['sid'], - } + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_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: UserBindingContext for this UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext + :returns: Machine friendly representation """ - 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 + return "" - @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 +class UserBindingList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): """ - return self._properties['account_sid'] + Initialize the UserBindingList + + :param version: Version that contains the resource + :param service_sid: + :param user_sid: - @property - def service_sid(self): """ - :returns: The SID of the Service that the resource is associated with - :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}/Bindings".format( + **self._solution + ) + + def stream( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserBindingInstance]: """ - return self._properties['service_sid'] + 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): + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :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 = self.page(binding_type=binding_type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserBindingInstance]: """ - return self._properties['date_created'] + 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_updated(self): + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :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 = await self.page_async( + binding_type=binding_type, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_updated'] + Streams UserBindingInstance and returns headers from first page - @property - def endpoint(self): + + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The unique endpoint identifier for the User Binding - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + binding_type=binding_type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['endpoint'] + Asynchronously streams UserBindingInstance and returns headers from first page - @property - def identity(self): + + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The string that identifies the resource's User - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + binding_type=binding_type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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): + :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 """ - :returns: The SID of the User with the binding - :rtype: unicode + + return list( + self.stream( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserBindingInstance]: """ - return self._properties['user_sid'] + 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. - @property - def credential_sid(self): + :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 """ - :returns: The SID of the Credential for the binding - :rtype: unicode + + return [ + record + async for record in await self.stream_async( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserBindingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserBindingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with UserBindingPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserBindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with UserBindingPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserBindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 1f9da08718..db12f64be8 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,1117 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class UserChannelList(ListResource): - """ """ +class UserChannelInstance(InstanceResource): + + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOT_PARTICIPATING = "not_participating" + + class NotificationLevel(object): + DEFAULT = "default" + MUTED = "muted" - def __init__(self, version, service_sid, user_sid): + """ + :ivar account_sid: + :ivar service_sid: + :ivar channel_sid: + :ivar user_sid: + :ivar member_sid: + :ivar status: + :ivar last_consumed_message_index: + :ivar unread_messages_count: + :ivar links: + :ivar url: + :ivar notification_level: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + user_sid: str, + channel_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.member_sid: Optional[str] = payload.get("member_sid") + self.status: Optional["UserChannelInstance.ChannelStatus"] = payload.get( + "status" + ) + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + self.notification_level: Optional["UserChannelInstance.NotificationLevel"] = ( + payload.get("notification_level") + ) + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "channel_sid": channel_sid or self.channel_sid, + } + + self._context: Optional[UserChannelContext] = None + + @property + def _proxy(self) -> "UserChannelContext": """ - Initialize the UserChannelList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param user_sid: The SID of the User the User Channel belongs to + :returns: UserChannelContext for this UserChannelInstance + """ + if self._context is None: + self._context = UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return self._context - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelList + def delete(self) -> bool: """ - super(UserChannelList, self).__init__(version) + Deletes the UserChannelInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'user_sid': user_sid, } - self._uri = '/Services/{service_sid}/Users/{user_sid}/Channels'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - Streams UserChannelInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserChannelInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserChannelInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists UserChannelInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserChannelInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_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, }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "UserChannelInstance": + """ + Asynchronous coroutine to fetch the UserChannelInstance - return UserChannelPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched UserChannelInstance """ - Retrieve a specific page of UserChannelInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserChannelInstance with HTTP info - :returns: Page of UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> "UserChannelInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: The updated UserChannelInstance + """ + return self._proxy.update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, ) - return UserChannelPage(self._version, response, self._solution) + async def update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> "UserChannelInstance": + """ + Asynchronous coroutine to update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: - def get(self, channel_sid): + :returns: The updated UserChannelInstance """ - Constructs a UserChannelContext + 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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserChannelInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return UserChannelContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - channel_sid=channel_sid, + return self._proxy.update_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: """ - Constructs a UserChannelContext + Asynchronous coroutine to update the UserChannelInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - 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_with_http_info_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 + 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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of UserChannelInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return UserChannelInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], + Deletes the UserChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserChannelInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the UserChannelInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserChannelInstance and return response metadata -class UserChannelContext(InstanceContext): - """ """ - def __init__(self, version, service_sid, user_sid, channel_sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the UserChannelContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext + Returns: + tuple: (payload, status_code, headers) """ - 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({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", 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, ) + payload, _, _ = self._fetch() + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserChannelInstance and return response metadata + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> UserChannelInstance: + """ + Asynchronous coroutine to fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + payload, _, _ = await self._fetch_async() 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_with_http_info_async(self) -> ApiResponse: """ - Deletes the UserChannelInstance + Asynchronous coroutine to fetch the UserChannelInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" - def update(self, notification_level=values.unset, - last_consumed_message_index=values.unset, - last_consumption_timestamp=values.unset): + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + 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_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the UserChannelInstance and return response metadata - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: + """ + Asynchronous coroutine to update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: The updated UserChannelInstance + """ + payload, _, _ = await self._update_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) 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"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserChannelInstance and return response metadata + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 UserChannelInstance(InstanceResource): - """ """ +class UserChannelPage(Page): - class ChannelStatus(object): - JOINED = "joined" - INVITED = "invited" - NOT_PARTICIPATING = "not_participating" + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: + """ + Build an instance of UserChannelInstance - class NotificationLevel(object): - DEFAULT = "default" - MUTED = "muted" + :param payload: Payload response from the API + """ - def __init__(self, version, payload, service_sid, user_sid, channel_sid=None): + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: """ - Initialize the UserChannelInstance + Provide a friendly representation - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance + :returns: Machine friendly representation """ - super(UserChannelInstance, self).__init__(version) + return "" - # Marshaled Properties - self._properties = { - 'account_sid': payload.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 +class UserChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserChannelList + + :param version: Version that contains the resource + :param service_sid: + :param user_sid: + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'user_sid': user_sid, - 'channel_sid': channel_sid or self._properties['channel_sid'], + "service_sid": service_sid, + "user_sid": user_sid, } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Channels".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserChannelInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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: UserChannelContext for this UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = UserChannelContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - channel_sid=self._solution['channel_sid'], - ) - return self._context + 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[UserChannelInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Asynchronously streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + Streams UserChannelInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['service_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def channel_sid(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Channel the resource belongs to - :rtype: unicode + Asynchronously streams UserChannelInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['channel_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def user_sid(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: """ - :returns: The SID of the User the User Channel belongs to - :rtype: unicode + Lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['user_sid'] - @property - def member_sid(self): + return 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]: """ - :returns: The SID of the User as a Member in the Channel - :rtype: unicode + Asynchronously lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['member_sid'] - @property - def status(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The status of the User on the Channel - :rtype: UserChannelInstance.ChannelStatus + Lists UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['status'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def last_consumed_message_index(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The index of the last Message in the Channel the Member has read - :rtype: unicode + Asynchronously lists UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['last_consumed_message_index'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def unread_messages_count(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, + ) -> UserChannelPage: """ - :returns: The number of unread Messages in the Channel for the User - :rtype: unicode + Retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance """ - return self._properties['unread_messages_count'] + 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 UserChannelPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: """ - :returns: Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel - :rtype: unicode + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance """ - return self._properties['links'] + 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 UserChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The absolute URL of the resource - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserChannelPage, status code, and headers """ - return self._properties['url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def notification_level(self): + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The push notification level of the User for the Channel - :rtype: UserChannelInstance.NotificationLevel + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserChannelPage, status code, and headers """ - return self._properties['notification_level'] + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> UserChannelPage: """ - Fetch the UserChannelInstance + Retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately - :returns: The fetched UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, solution=self._solution) - def delete(self): + async def get_page_async(self, target_url: str) -> UserChannelPage: """ - Deletes the UserChannelInstance + Asynchronously retrieve a specific page of UserChannelInstance 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 UserChannelInstance """ - return self._proxy.delete() + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserChannelPage(self._version, response, solution=self._solution) - def update(self, notification_level=values.unset, - last_consumed_message_index=values.unset, - last_consumption_timestamp=values.unset): + def get(self, channel_sid: str) -> UserChannelContext: """ - Update the UserChannelInstance + Constructs a UserChannelContext + + :param channel_sid: + """ + return UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=channel_sid, + ) - :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/knowledge/KnowledgeBase.py b/twilio/rest/knowledge/KnowledgeBase.py new file mode 100644 index 0000000000..c92fd50540 --- /dev/null +++ b/twilio/rest/knowledge/KnowledgeBase.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.knowledge.v1 import V1 +from twilio.rest.knowledge.v2 import V2 + + +class KnowledgeBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Knowledge Domain + + :returns: Domain for Knowledge + """ + super().__init__(twilio, "https://knowledge.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Knowledge + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Knowledge + """ + 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/knowledge/__init__.py b/twilio/rest/knowledge/__init__.py new file mode 100644 index 0000000000..ed6256683a --- /dev/null +++ b/twilio/rest/knowledge/__init__.py @@ -0,0 +1,5 @@ +from twilio.rest.knowledge.KnowledgeBase import KnowledgeBase + + +class Knowledge(KnowledgeBase): + pass diff --git a/twilio/rest/knowledge/v1/__init__.py b/twilio/rest/knowledge/v1/__init__.py new file mode 100644 index 0000000000..9609bff951 --- /dev/null +++ b/twilio/rest/knowledge/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Knowledge + This is the public Twilio 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.knowledge.v1.knowledge import KnowledgeList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Knowledge + + :param domain: The Twilio.knowledge domain + """ + super().__init__(domain, "v1") + self._knowledge: Optional[KnowledgeList] = None + + @property + def knowledge(self) -> KnowledgeList: + if self._knowledge is None: + self._knowledge = KnowledgeList(self) + return self._knowledge + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/knowledge/v1/knowledge/__init__.py b/twilio/rest/knowledge/v1/knowledge/__init__.py new file mode 100644 index 0000000000..55395f0737 --- /dev/null +++ b/twilio/rest/knowledge/v1/knowledge/__init__.py @@ -0,0 +1,1432 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Knowledge + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do 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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.knowledge.v1.knowledge.chunk import ChunkList +from twilio.rest.knowledge.v1.knowledge.knowledge_status import KnowledgeStatusList + + +class KnowledgeInstance(InstanceResource): + + class KnowledgeV1ServiceCreateKnowledgeRequest(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 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.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.KnowledgeV1ServiceCreatePolicyRequest + ] = 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, + } + + class KnowledgeV1ServiceCreatePolicyRequest(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 KnowledgeV1ServiceUpdateKnowledgeRequest(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.KnowledgeV1ServiceCreatePolicyRequest + ] = 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> "KnowledgeInstance": + """ + Update the KnowledgeInstance + + :param knowledge_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + return self._proxy.update( + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request, + ) + + async def update_async( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> "KnowledgeInstance": + """ + Asynchronous coroutine to update the KnowledgeInstance + + :param knowledge_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + return await self._proxy.update_async( + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request, + ) + + def update_with_http_info( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeInstance with HTTP info + + :param knowledge_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request, + ) + + async def update_with_http_info_async( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeInstance with HTTP info + + :param knowledge_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + knowledge_v1_service_update_knowledge_request=knowledge_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 KnowledgeV1ServiceCreateKnowledgeRequest(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 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.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.KnowledgeV1ServiceCreatePolicyRequest + ] = 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, + } + + class KnowledgeV1ServiceCreatePolicyRequest(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 KnowledgeV1ServiceUpdateKnowledgeRequest(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.KnowledgeV1ServiceCreatePolicyRequest + ] = 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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the KnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> KnowledgeInstance: + """ + Fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + payload, _, _ = self._fetch() + return KnowledgeInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = KnowledgeInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> KnowledgeInstance: + """ + Asynchronous coroutine to fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + payload, _, _ = await self._fetch_async() + return KnowledgeInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = KnowledgeInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_v1_service_update_knowledge_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> KnowledgeInstance: + """ + Update the KnowledgeInstance + + :param knowledge_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + payload, _, _ = self._update( + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request + ) + return KnowledgeInstance(self._version, payload, id=self._solution["id"]) + + def update_with_http_info( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeInstance and return response metadata + + :param knowledge_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request + ) + instance = KnowledgeInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_v1_service_update_knowledge_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> KnowledgeInstance: + """ + Asynchronous coroutine to update the KnowledgeInstance + + :param knowledge_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + payload, _, _ = await self._update_async( + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request + ) + return KnowledgeInstance(self._version, payload, id=self._solution["id"]) + + async def update_with_http_info_async( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeInstance and return response metadata + + :param knowledge_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request + ) + instance = KnowledgeInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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 KnowledgeV1ServiceCreateKnowledgeRequest(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 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.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.KnowledgeV1ServiceCreatePolicyRequest + ] = 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, + } + + class KnowledgeV1ServiceCreatePolicyRequest(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 KnowledgeV1ServiceUpdateKnowledgeRequest(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.KnowledgeV1ServiceCreatePolicyRequest + ] = 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, + knowledge_v1_service_create_knowledge_request: KnowledgeV1ServiceCreateKnowledgeRequest, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + knowledge_v1_service_create_knowledge_request: KnowledgeV1ServiceCreateKnowledgeRequest, + ) -> KnowledgeInstance: + """ + Create the KnowledgeInstance + + :param knowledge_v1_service_create_knowledge_request: + + :returns: The created KnowledgeInstance + """ + payload, _, _ = self._create( + knowledge_v1_service_create_knowledge_request=knowledge_v1_service_create_knowledge_request + ) + return KnowledgeInstance(self._version, payload) + + def create_with_http_info( + self, + knowledge_v1_service_create_knowledge_request: KnowledgeV1ServiceCreateKnowledgeRequest, + ) -> ApiResponse: + """ + Create the KnowledgeInstance and return response metadata + + :param knowledge_v1_service_create_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + knowledge_v1_service_create_knowledge_request=knowledge_v1_service_create_knowledge_request + ) + instance = KnowledgeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + knowledge_v1_service_create_knowledge_request: KnowledgeV1ServiceCreateKnowledgeRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + knowledge_v1_service_create_knowledge_request: KnowledgeV1ServiceCreateKnowledgeRequest, + ) -> KnowledgeInstance: + """ + Asynchronously create the KnowledgeInstance + + :param knowledge_v1_service_create_knowledge_request: + + :returns: The created KnowledgeInstance + """ + payload, _, _ = await self._create_async( + knowledge_v1_service_create_knowledge_request=knowledge_v1_service_create_knowledge_request + ) + return KnowledgeInstance(self._version, payload) + + async def create_with_http_info_async( + self, + knowledge_v1_service_create_knowledge_request: KnowledgeV1ServiceCreateKnowledgeRequest, + ) -> ApiResponse: + """ + Asynchronously create the KnowledgeInstance and return response metadata + + :param knowledge_v1_service_create_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + knowledge_v1_service_create_knowledge_request=knowledge_v1_service_create_knowledge_request + ) + instance = KnowledgeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + tags: 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 tags: Json array of tag and value pairs for tag filtering. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(tags=tags, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + tags: 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 tags: Json array of tag and value pairs for tag filtering. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(tags=tags, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + tags: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams KnowledgeInstance and returns headers from first page + + + :param str tags: Json array of tag and value pairs for tag filtering. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + tags=tags, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + tags: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams KnowledgeInstance and returns headers from first page + + + :param str tags: Json array of tag and value pairs for tag filtering. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + tags=tags, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + tags: 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 tags: Json array of tag and value pairs for tag filtering. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + tags=tags, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + tags: 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 tags: Json array of tag and value pairs for tag filtering. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + tags=tags, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + tags: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists KnowledgeInstance and returns headers from first page + + + :param str tags: Json array of tag and value pairs for tag filtering. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + tags=tags, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + tags: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists KnowledgeInstance and returns headers from first page + + + :param str tags: Json array of tag and value pairs for tag filtering. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + tags=tags, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + tags: Union[str, 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 tags: Json array of tag and value pairs for tag filtering. + :param page_token: PageToken provided by the API + :param page_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( + { + "Tags": tags, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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, + tags: Union[str, 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 tags: Json array of tag and value pairs for tag filtering. + :param page_token: PageToken provided by the API + :param page_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( + { + "Tags": tags, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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 page_with_http_info( + self, + tags: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param tags: Json array of tag and value pairs for tag filtering. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with KnowledgePage, status code, and headers + """ + data = values.of( + { + "Tags": tags, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = KnowledgePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + tags: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param tags: Json array of tag and value pairs for tag filtering. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with KnowledgePage, status code, and headers + """ + data = values.of( + { + "Tags": tags, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = KnowledgePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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/knowledge/v1/knowledge/chunk.py b/twilio/rest/knowledge/v1/knowledge/chunk.py new file mode 100644 index 0000000000..97dbe422d6 --- /dev/null +++ b/twilio/rest/knowledge/v1/knowledge/chunk.py @@ -0,0 +1,471 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Knowledge + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do 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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChunkInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChunkInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChunkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChunkPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChunkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChunkPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/knowledge/v1/knowledge/knowledge_status.py b/twilio/rest/knowledge/v1/knowledge/knowledge_status.py new file mode 100644 index 0000000000..950318b3ac --- /dev/null +++ b/twilio/rest/knowledge/v1/knowledge/knowledge_status.py @@ -0,0 +1,264 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Knowledge + This is the public Twilio REST API. + + NOTE: This class is 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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> KnowledgeStatusInstance: + """ + Fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + payload, _, _ = self._fetch() + return KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeStatusInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> KnowledgeStatusInstance: + """ + Asynchronous coroutine to fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + payload, _, _ = await self._fetch_async() + return KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeStatusInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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/knowledge/v2/__init__.py b/twilio/rest/knowledge/v2/__init__.py new file mode 100644 index 0000000000..f329d0911d --- /dev/null +++ b/twilio/rest/knowledge/v2/__init__.py @@ -0,0 +1,96 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Knowledge API + APIs for managing knowledge bases and knowledge content for AI-powered applications. + + NOTE: This 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.knowledge.v2.chunk import ChunkList +from twilio.rest.knowledge.v2.knowledge import KnowledgeList +from twilio.rest.knowledge.v2.knowledge_basis import KnowledgeBasisList +from twilio.rest.knowledge.v2.operation import OperationList +from twilio.rest.knowledge.v2.search import SearchList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Knowledge + + :param domain: The Twilio.knowledge domain + """ + super().__init__(domain, "v2") + self._knowledge_bases: Optional[KnowledgeBasisList] = None + self._operations: Optional[OperationList] = None + + def chunks(self, kb_id: str, knowledge_id: str, chunk_id: str = None): + """ + Access the ChunkList resource + + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + + :param knowledge_id: A unique Knowledge resource ID using Twilio Type ID (TTID) format + + :param chunk_id: Optional instance ID to directly access ChunkContext + :returns: ChunkList instance if chunk_id is None, otherwise ChunkContext + """ + list_instance = ChunkList(self, kb_id, knowledge_id) + if chunk_id is not None: + return list_instance(chunk_id) + return list_instance + + def knowledge(self, kb_id: str, knowledge_id: str = None): + """ + Access the KnowledgeList resource + + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + + :param knowledge_id: Optional instance ID to directly access KnowledgeContext + :returns: KnowledgeList instance if knowledge_id is None, otherwise KnowledgeContext + """ + list_instance = KnowledgeList(self, kb_id) + if knowledge_id is not None: + return list_instance(knowledge_id) + return list_instance + + @property + def knowledge_bases(self) -> KnowledgeBasisList: + if self._knowledge_bases is None: + self._knowledge_bases = KnowledgeBasisList(self) + return self._knowledge_bases + + @property + def operations(self) -> OperationList: + if self._operations is None: + self._operations = OperationList(self) + return self._operations + + def search(self, kb_id: str, search_id: str = None): + """ + Access the SearchList resource + + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + + :param search_id: Optional instance ID to directly access SearchContext + :returns: SearchList instance if search_id is None, otherwise SearchContext + """ + list_instance = SearchList(self) + return list_instance(kb_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/knowledge/v2/chunk.py b/twilio/rest/knowledge/v2/chunk.py new file mode 100644 index 0000000000..6537de31a8 --- /dev/null +++ b/twilio/rest/knowledge/v2/chunk.py @@ -0,0 +1,505 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Knowledge API + APIs for managing knowledge bases and knowledge content for AI-powered applications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ChunkInstance(InstanceResource): + """ + :ivar content: The chunk content. + :ivar created_at: The date and time in GMT when the Chunk was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], kb_id: str, knowledge_id: str + ): + super().__init__(version) + + self.content: Optional[str] = payload.get("content") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + + # Only set _solution if path params are provided (not None) + if kb_id is not None or knowledge_id is not None: + self._solution = { + "kb_id": kb_id, + "knowledge_id": knowledge_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(TokenPagination): + + 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, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ChunkList(ListResource): + + def __init__(self, version: Version, kb_id: str, knowledge_id: str): + """ + Initialize the ChunkList + + :param version: Version that contains the resource + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + :param knowledge_id: A unique Knowledge resource ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "kb_id": kb_id, + "knowledge_id": knowledge_id, + } + self._uri = "/KnowledgeBases/{kb_id}/Knowledge/{knowledge_id}/Chunks".format( + **self._solution + ) + + def stream( + self, + page_token: Union[str, object] = values.unset, + 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 str page_token: The page token. This is provided by the API. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_token=page_token, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + 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 str page_token: The page token. This is provided by the API. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChunkInstance and returns headers from first page + + + :param str page_token: The page token. This is provided by the API. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChunkInstance and returns headers from first page + + + :param str page_token: The page token. This is provided by the API. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + 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 str page_token: The page token. This is provided by 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: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + 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 str page_token: The page token. This is provided by 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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChunkInstance and returns headers from first page + + + :param str page_token: The page token. This is provided by 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChunkInstance and returns headers from first page + + + :param str page_token: The page token. This is provided by 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ChunkPage: + """ + Retrieve a single page of ChunkInstance records from the API. + Request is executed immediately + + :param page_size: How many resources to return in each list page. The default is 50, and the maximum is 1000. + :param page_token: The page token. This is provided by the API. + :returns: Page of ChunkInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-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, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ChunkPage: + """ + Asynchronously retrieve a single page of ChunkInstance records from the API. + Request is executed immediately + + :param page_size: How many resources to return in each list page. The default is 50, and the maximum is 1000. + :param page_token: The page token. This is provided by the API. + :returns: Page of ChunkInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/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, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The page token. This is provided by the API. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChunkPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChunkPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The page token. This is provided by the API. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChunkPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChunkPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/knowledge/v2/knowledge.py b/twilio/rest/knowledge/v2/knowledge.py new file mode 100644 index 0000000000..446135b3cc --- /dev/null +++ b/twilio/rest/knowledge/v2/knowledge.py @@ -0,0 +1,1249 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Knowledge API + APIs for managing knowledge bases and knowledge content for AI-powered applications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class KnowledgeInstance(InstanceResource): + + class SupportedFileMimeType(object): + TEXT_CSV = "text/csv" + TEXT_MARKDOWN = "text/markdown" + TEXT_MDX = "text/mdx" + APPLICATION_PDF = "application/pdf" + TEXT_TAB_SEPARATED_VALUES = "text/tab-separated-values" + TEXT_PLAIN = "text/plain" + + """ + :ivar name: The name of the knowledge source. + :ivar description: A detailed description of the knowledge source and when to use it. This helps provide context about the content and its intended purpose. + :ivar source: + :ivar id: The unique identifier of knowledge source. + :ivar status: The status of processing the knowledge source ('SCHEDULED', 'QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED'). + :ivar created_at: The date and time in GMT when the Knowledge was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar updated_at: The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar code: The Twilio error code. + :ivar message: A human readable message describing the error. + :ivar more_info: A URL to a [Twilio error directory](https://www.twilio.com/docs/api/errors) page with more information about the error code. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + kb_id: str, + knowledge_id: Optional[str] = None, + ): + super().__init__(version) + + self.name: Optional[str] = payload.get("name") + self.description: Optional[str] = payload.get("description") + self.source: Optional[str] = payload.get("source") + self.id: Optional[str] = payload.get("id") + self.status: Optional["KnowledgeInstance.str"] = payload.get("status") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.more_info: Optional[str] = payload.get("more_info") + + # Only set _solution if path params are provided (not None) + if kb_id is not None or knowledge_id is not None: + self._solution = { + "kb_id": kb_id, + "knowledge_id": knowledge_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, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> "KnowledgeInstance": + """ + Update the KnowledgeInstance + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: The updated KnowledgeInstance + """ + return self._proxy.update( + refresh=refresh, + knowledge_core=knowledge_core, + ) + + async def update_async( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> "KnowledgeInstance": + """ + Asynchronous coroutine to update the KnowledgeInstance + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: The updated KnowledgeInstance + """ + return await self._proxy.update_async( + refresh=refresh, + knowledge_core=knowledge_core, + ) + + def update_with_http_info( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeInstance with HTTP info + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + refresh=refresh, + knowledge_core=knowledge_core, + ) + + async def update_with_http_info_async( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeInstance with HTTP info + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + refresh=refresh, + knowledge_core=knowledge_core, + ) + + def __repr__(self) -> str: + """ + 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): + + def __init__(self, version: Version, kb_id: str, knowledge_id: str): + """ + Initialize the KnowledgeContext + + :param version: Version that contains the resource + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + :param knowledge_id: A unique Knowledge resource ID using Twilio Type ID (TTID) format + """ + super().__init__(version) + + # Path Solution + self._solution = { + "kb_id": kb_id, + "knowledge_id": knowledge_id, + } + self._uri = "/KnowledgeBases/{kb_id}/Knowledge/{knowledge_id}".format( + **self._solution + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the KnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> KnowledgeInstance: + """ + Fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + payload, _, _ = self._fetch() + return KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> KnowledgeInstance: + """ + Asynchronous coroutine to fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + payload, _, _ = await self._fetch_async() + return KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_core.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + params = values.of( + { + "refresh": serialize.boolean_to_string(refresh), + } + ) + + return self._version.update_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers, params=params + ) + + def update( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> KnowledgeInstance: + """ + Update the KnowledgeInstance + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: The updated KnowledgeInstance + """ + payload, _, _ = self._update(refresh=refresh, knowledge_core=knowledge_core) + return KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + + def update_with_http_info( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeInstance and return response metadata + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + refresh=refresh, knowledge_core=knowledge_core + ) + instance = KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_core.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + params = values.of( + { + "refresh": serialize.boolean_to_string(refresh), + } + ) + + return await self._version.update_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers, params=params + ) + + async def update_async( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> KnowledgeInstance: + """ + Asynchronous coroutine to update the KnowledgeInstance + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: The updated KnowledgeInstance + """ + payload, _, _ = await self._update_async( + refresh=refresh, knowledge_core=knowledge_core + ) + return KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + + async def update_with_http_info_async( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeInstance and return response metadata + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + refresh=refresh, knowledge_core=knowledge_core + ) + instance = KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 KnowledgePage(TokenPagination): + + 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, kb_id=self._solution["kb_id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class KnowledgeList(ListResource): + + class KnowledgeCore(object): + """ + :ivar name: The name of the knowledge source. + :ivar description: A detailed description of the knowledge source and when to use it. This helps provide context about the content and its intended purpose. + :ivar source: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.description: Optional[str] = payload.get("description") + self.source: Optional[KnowledgeList.KnowledgeSourceTypes] = payload.get( + "source" + ) + + def to_dict(self): + return { + "name": self.name, + "description": self.description, + "source": self.source.to_dict() if self.source is not None else None, + } + + class KnowledgeSourceTypes(object): + """ + :ivar type: Raw text knowledge sources + :ivar content: The raw text content to be processed + :ivar url: The URL to crawl for web content + :ivar crawl_depth: The maximum depth to crawl from the source URL + :ivar crawl_period: Frequency of re-crawling the website for updated content + :ivar file_name: Name of the file to be uploaded + :ivar file_size: Expected size of the file in bytes + :ivar mime_type: + :ivar import_url: Presigned S3 URL for file upload (when status is SCHEDULED) or the permanent S3 location after upload completes. Use PUT method to upload the file to this URL when status is SCHEDULED. + :ivar upload_expiration: Expiration time of the presigned upload URL in ISO 8601 format (only present when status is SCHEDULED) + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["KnowledgeInstance.str"] = payload.get("type") + self.content: Optional[str] = payload.get("content") + self.url: Optional[str] = payload.get("url") + self.crawl_depth: Optional[int] = payload.get("crawlDepth") + self.crawl_period: Optional["KnowledgeInstance.str"] = payload.get( + "crawlPeriod" + ) + self.file_name: Optional[str] = payload.get("fileName") + self.file_size: Optional[int] = payload.get("fileSize") + self.mime_type: Optional["KnowledgeInstance.SupportedFileMimeType"] = ( + payload.get("mimeType") + ) + self.import_url: Optional[str] = payload.get("importUrl") + self.upload_expiration: Optional[datetime] = payload.get("uploadExpiration") + + def to_dict(self): + return { + "type": self.type, + "content": self.content, + "url": self.url, + "crawlDepth": self.crawl_depth, + "crawlPeriod": self.crawl_period, + "fileName": self.file_name, + "fileSize": self.file_size, + "mimeType": self.mime_type, + "importUrl": self.import_url, + "uploadExpiration": self.upload_expiration, + } + + def __init__(self, version: Version, kb_id: str): + """ + Initialize the KnowledgeList + + :param version: Version that contains the resource + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "kb_id": kb_id, + } + self._uri = "/KnowledgeBases/{kb_id}/Knowledge".format(**self._solution) + + def _create(self, knowledge_core: KnowledgeCore) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_core.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, knowledge_core: KnowledgeCore) -> KnowledgeInstance: + """ + Create the KnowledgeInstance + + :param knowledge_core: + + :returns: The created KnowledgeInstance + """ + payload, _, _ = self._create(knowledge_core=knowledge_core) + return KnowledgeInstance(self._version, payload, kb_id=self._solution["kb_id"]) + + def create_with_http_info(self, knowledge_core: KnowledgeCore) -> ApiResponse: + """ + Create the KnowledgeInstance and return response metadata + + :param knowledge_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(knowledge_core=knowledge_core) + instance = KnowledgeInstance( + self._version, payload, kb_id=self._solution["kb_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, knowledge_core: KnowledgeCore) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_core.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, knowledge_core: KnowledgeCore) -> KnowledgeInstance: + """ + Asynchronously create the KnowledgeInstance + + :param knowledge_core: + + :returns: The created KnowledgeInstance + """ + payload, _, _ = await self._create_async(knowledge_core=knowledge_core) + return KnowledgeInstance(self._version, payload, kb_id=self._solution["kb_id"]) + + async def create_with_http_info_async( + self, knowledge_core: KnowledgeCore + ) -> ApiResponse: + """ + Asynchronously create the KnowledgeInstance and return response metadata + + :param knowledge_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + knowledge_core=knowledge_core + ) + instance = KnowledgeInstance( + self._version, payload, kb_id=self._solution["kb_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page: Union[int, object] = values.unset, + page_token: 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 int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page=page, page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page: Union[int, object] = values.unset, + page_token: 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 int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page=page, page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams KnowledgeInstance and returns headers from first page + + + :param int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page=page, page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams KnowledgeInstance and returns headers from first page + + + :param int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page=page, page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page: Union[int, object] = values.unset, + page_token: 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 int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page=page, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page: Union[int, object] = values.unset, + page_token: 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 int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page=page, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists KnowledgeInstance and returns headers from first page + + + :param int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page=page, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists KnowledgeInstance and returns headers from first page + + + :param int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page=page, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> KnowledgePage: + """ + Retrieve a single page of KnowledgeInstance records from the API. + Request is executed immediately + + :param page: The page index. This value is simply for client state. + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :returns: Page of KnowledgeInstance + """ + data = values.of( + { + "page": page, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-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, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> KnowledgePage: + """ + Asynchronously retrieve a single page of KnowledgeInstance records from the API. + Request is executed immediately + + :param page: The page index. This value is simply for client state. + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :returns: Page of KnowledgeInstance + """ + data = values.of( + { + "page": page, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/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, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page: The page index. This value is simply for client state. + :param page_token: The token for the page of results to retrieve. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with KnowledgePage, status code, and headers + """ + data = values.of( + { + "page": page, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = KnowledgePage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page: The page index. This value is simply for client state. + :param page_token: The token for the page of results to retrieve. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with KnowledgePage, status code, and headers + """ + data = values.of( + { + "page": page, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = KnowledgePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=self._solution) + + 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, solution=self._solution) + + def get(self, knowledge_id: str) -> KnowledgeContext: + """ + Constructs a KnowledgeContext + + :param knowledge_id: A unique Knowledge resource ID using Twilio Type ID (TTID) format + """ + return KnowledgeContext( + self._version, kb_id=self._solution["kb_id"], knowledge_id=knowledge_id + ) + + def __call__(self, knowledge_id: str) -> KnowledgeContext: + """ + Constructs a KnowledgeContext + + :param knowledge_id: A unique Knowledge resource ID using Twilio Type ID (TTID) format + """ + return KnowledgeContext( + self._version, kb_id=self._solution["kb_id"], knowledge_id=knowledge_id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/knowledge/v2/knowledge_basis.py b/twilio/rest/knowledge/v2/knowledge_basis.py new file mode 100644 index 0000000000..629b2083b9 --- /dev/null +++ b/twilio/rest/knowledge/v2/knowledge_basis.py @@ -0,0 +1,1172 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Knowledge API + APIs for managing knowledge bases and knowledge content for AI-powered applications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class KnowledgeBasisInstance(InstanceResource): + """ + :ivar message: + :ivar display_name: Provides a unique and addressable name to be assigned to this Knowledge Base. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + :ivar description: A human readable description of this resource, up to 128 characters. + :ivar id: The unique identifier for the Knowledge Base + :ivar status: The provisioning status of the Knowledge Base + :ivar created_at: The ISO 8601 timestamp when the Knowledge Base was created. + :ivar updated_at: The ISO 8601 timestamp when the Knowledge Base was last updated. + :ivar version: The current version number of the Knowledge Base. Incremented on each successful mutable update. + :ivar status_url: URI to check operation status. + """ + + def __init__( + self, version: Version, payload: ResponseResource, kb_id: Optional[str] = None + ): + super().__init__(version) + + self.message: Optional[str] = payload.get("message") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.status: Optional["KnowledgeBasisInstance.str"] = payload.get("status") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.status_url: Optional[str] = payload.get("statusUrl") + + # Only set _solution if path params are provided (not None) + if kb_id is not None: + self._solution = { + "kb_id": kb_id, + } + + self._context: Optional[KnowledgeBasisContext] = None + + @property + def _proxy(self) -> "KnowledgeBasisContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: KnowledgeBasisContext for this KnowledgeBasisInstance + """ + if self._context is None: + self._context = KnowledgeBasisContext( + self._version, + kb_id=self._solution["kb_id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the KnowledgeBasisInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the KnowledgeBasisInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KnowledgeBasisInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KnowledgeBasisInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "KnowledgeBasisInstance": + """ + Fetch the KnowledgeBasisInstance + + + :returns: The fetched KnowledgeBasisInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "KnowledgeBasisInstance": + """ + Asynchronous coroutine to fetch the KnowledgeBasisInstance + + + :returns: The fetched KnowledgeBasisInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeBasisInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeBasisInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> "KnowledgeBasisInstance": + """ + Update the KnowledgeBasisInstance + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: The updated KnowledgeBasisInstance + """ + return self._proxy.update( + update_knowledge_base_request=update_knowledge_base_request, + if_match=if_match, + ) + + async def update_async( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> "KnowledgeBasisInstance": + """ + Asynchronous coroutine to update the KnowledgeBasisInstance + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: The updated KnowledgeBasisInstance + """ + return await self._proxy.update_async( + update_knowledge_base_request=update_knowledge_base_request, + if_match=if_match, + ) + + def update_with_http_info( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeBasisInstance with HTTP info + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + update_knowledge_base_request=update_knowledge_base_request, + if_match=if_match, + ) + + async def update_with_http_info_async( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeBasisInstance with HTTP info + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + update_knowledge_base_request=update_knowledge_base_request, + 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 KnowledgeBasisContext(InstanceContext): + + def __init__(self, version: Version, kb_id: str): + """ + Initialize the KnowledgeBasisContext + + :param version: Version that contains the resource + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + """ + super().__init__(version) + + # Path Solution + self._solution = { + "kb_id": kb_id, + } + self._uri = "/ControlPlane/KnowledgeBases/{kb_id}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the KnowledgeBasisInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KnowledgeBasisInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the KnowledgeBasisInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KnowledgeBasisInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> KnowledgeBasisInstance: + """ + Fetch the KnowledgeBasisInstance + + + :returns: The fetched KnowledgeBasisInstance + """ + payload, _, _ = self._fetch() + return KnowledgeBasisInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeBasisInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = KnowledgeBasisInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> KnowledgeBasisInstance: + """ + Asynchronous coroutine to fetch the KnowledgeBasisInstance + + + :returns: The fetched KnowledgeBasisInstance + """ + payload, _, _ = await self._fetch_async() + return KnowledgeBasisInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeBasisInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = KnowledgeBasisInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_knowledge_base_request.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["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> KnowledgeBasisInstance: + """ + Update the KnowledgeBasisInstance + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: The updated KnowledgeBasisInstance + """ + payload, _, _ = self._update( + update_knowledge_base_request=update_knowledge_base_request, + if_match=if_match, + ) + return KnowledgeBasisInstance( + self._version, payload, kb_id=self._solution["kb_id"] + ) + + def update_with_http_info( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeBasisInstance and return response metadata + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + update_knowledge_base_request=update_knowledge_base_request, + if_match=if_match, + ) + instance = KnowledgeBasisInstance( + self._version, payload, kb_id=self._solution["kb_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_knowledge_base_request.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["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> KnowledgeBasisInstance: + """ + Asynchronous coroutine to update the KnowledgeBasisInstance + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: The updated KnowledgeBasisInstance + """ + payload, _, _ = await self._update_async( + update_knowledge_base_request=update_knowledge_base_request, + if_match=if_match, + ) + return KnowledgeBasisInstance( + self._version, payload, kb_id=self._solution["kb_id"] + ) + + async def update_with_http_info_async( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeBasisInstance and return response metadata + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + update_knowledge_base_request=update_knowledge_base_request, + if_match=if_match, + ) + instance = KnowledgeBasisInstance( + self._version, payload, kb_id=self._solution["kb_id"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 KnowledgeBasisPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> KnowledgeBasisInstance: + """ + Build an instance of KnowledgeBasisInstance + + :param payload: Payload response from the API + """ + + return KnowledgeBasisInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class KnowledgeBasisList(ListResource): + + class KnowledgeBaseCore(object): + """ + :ivar display_name: Provides a unique and addressable name to be assigned to this Knowledge Base. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + :ivar description: A human readable description of this resource, up to 128 characters. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + } + + class UpdateKnowledgeBaseRequest(object): + """ + :ivar display_name: Provides a unique and addressable name to be assigned to this Knowledge Base. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + :ivar description: A human readable description of this resource, up to 128 characters. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + } + + def __init__(self, version: Version): + """ + Initialize the KnowledgeBasisList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ControlPlane/KnowledgeBases" + + def _create(self, knowledge_base_core: KnowledgeBaseCore) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_base_core.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, knowledge_base_core: KnowledgeBaseCore) -> KnowledgeBasisInstance: + """ + Create the KnowledgeBasisInstance + + :param knowledge_base_core: + + :returns: The created KnowledgeBasisInstance + """ + payload, _, _ = self._create(knowledge_base_core=knowledge_base_core) + return KnowledgeBasisInstance(self._version, payload) + + def create_with_http_info( + self, knowledge_base_core: KnowledgeBaseCore + ) -> ApiResponse: + """ + Create the KnowledgeBasisInstance and return response metadata + + :param knowledge_base_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + knowledge_base_core=knowledge_base_core + ) + instance = KnowledgeBasisInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, knowledge_base_core: KnowledgeBaseCore) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_base_core.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, knowledge_base_core: KnowledgeBaseCore + ) -> KnowledgeBasisInstance: + """ + Asynchronously create the KnowledgeBasisInstance + + :param knowledge_base_core: + + :returns: The created KnowledgeBasisInstance + """ + payload, _, _ = await self._create_async( + knowledge_base_core=knowledge_base_core + ) + return KnowledgeBasisInstance(self._version, payload) + + async def create_with_http_info_async( + self, knowledge_base_core: KnowledgeBaseCore + ) -> ApiResponse: + """ + Asynchronously create the KnowledgeBasisInstance and return response metadata + + :param knowledge_base_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + knowledge_base_core=knowledge_base_core + ) + instance = KnowledgeBasisInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[KnowledgeBasisInstance]: + """ + Streams KnowledgeBasisInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[KnowledgeBasisInstance]: + """ + Asynchronously streams KnowledgeBasisInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams KnowledgeBasisInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams KnowledgeBasisInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KnowledgeBasisInstance]: + """ + Lists KnowledgeBasisInstance 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: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KnowledgeBasisInstance]: + """ + Asynchronously lists KnowledgeBasisInstance 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: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists KnowledgeBasisInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists KnowledgeBasisInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> KnowledgeBasisPage: + """ + Retrieve a single page of KnowledgeBasisInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of KnowledgeBasisInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KnowledgeBasisPage(self._version, response, uri=self._uri, params=data) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> KnowledgeBasisPage: + """ + Asynchronously retrieve a single page of KnowledgeBasisInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of KnowledgeBasisInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KnowledgeBasisPage(self._version, response, uri=self._uri, params=data) + + def page_with_http_info( + self, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with KnowledgeBasisPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = KnowledgeBasisPage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with KnowledgeBasisPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = KnowledgeBasisPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> KnowledgeBasisPage: + """ + Retrieve a specific page of KnowledgeBasisInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KnowledgeBasisInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return KnowledgeBasisPage(self._version, response) + + async def get_page_async(self, target_url: str) -> KnowledgeBasisPage: + """ + Asynchronously retrieve a specific page of KnowledgeBasisInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KnowledgeBasisInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return KnowledgeBasisPage(self._version, response) + + def get(self, kb_id: str) -> KnowledgeBasisContext: + """ + Constructs a KnowledgeBasisContext + + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + """ + return KnowledgeBasisContext(self._version, kb_id=kb_id) + + def __call__(self, kb_id: str) -> KnowledgeBasisContext: + """ + Constructs a KnowledgeBasisContext + + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + """ + return KnowledgeBasisContext(self._version, kb_id=kb_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/knowledge/v2/operation.py b/twilio/rest/knowledge/v2/operation.py new file mode 100644 index 0000000000..e967c1d8bd --- /dev/null +++ b/twilio/rest/knowledge/v2/operation.py @@ -0,0 +1,279 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Knowledge API + APIs for managing knowledge bases and knowledge content for AI-powered applications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.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 OperationInstance(InstanceResource): + """ + :ivar operation_id: The unique identifier for this operation. + :ivar status: The current status of the operation. + :ivar created_at: When the operation was created. + :ivar status_url: URI to check operation status. + :ivar completed_at: When the operation completed or failed. + :ivar result: + :ivar error: + :ivar result_url: URL to fetch the resulting resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + operation_id: Optional[str] = None, + ): + super().__init__(version) + + self.operation_id: Optional[str] = payload.get("operationId") + self.status: Optional["OperationInstance.str"] = payload.get("status") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.status_url: Optional[str] = payload.get("statusUrl") + self.completed_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("completedAt") + ) + self.result: Optional[str] = payload.get("result") + self.error: Optional[str] = payload.get("error") + self.result_url: Optional[str] = payload.get("resultUrl") + + # Only set _solution if path params are provided (not None) + if operation_id is not None: + self._solution = { + "operation_id": operation_id, + } + + self._context: Optional[OperationContext] = None + + @property + def _proxy(self) -> "OperationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperationContext for this OperationInstance + """ + if self._context is None: + self._context = OperationContext( + self._version, + operation_id=self._solution["operation_id"], + ) + return self._context + + def fetch(self) -> "OperationInstance": + """ + Fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperationInstance": + """ + Asynchronous coroutine to fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 OperationContext(InstanceContext): + + def __init__(self, version: Version, operation_id: str): + """ + Initialize the OperationContext + + :param version: Version that contains the resource + :param operation_id: The operation ID returned from a write endpoint. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "operation_id": operation_id, + } + self._uri = "/ControlPlane/Operations/{operation_id}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OperationInstance: + """ + Fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + payload, _, _ = self._fetch() + return OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OperationInstance: + """ + Asynchronous coroutine to fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + payload, _, _ = await self._fetch_async() + return OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 OperationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, operation_id: str) -> OperationContext: + """ + Constructs a OperationContext + + :param operation_id: The operation ID returned from a write endpoint. + """ + return OperationContext(self._version, operation_id=operation_id) + + def __call__(self, operation_id: str) -> OperationContext: + """ + Constructs a OperationContext + + :param operation_id: The operation ID returned from a write endpoint. + """ + return OperationContext(self._version, operation_id=operation_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/knowledge/v2/search.py b/twilio/rest/knowledge/v2/search.py new file mode 100644 index 0000000000..cf2f5ff87c --- /dev/null +++ b/twilio/rest/knowledge/v2/search.py @@ -0,0 +1,305 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Knowledge API + APIs for managing knowledge bases and knowledge content for AI-powered applications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse +from twilio.base.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 SearchInstance(InstanceResource): + """ + :ivar chunks: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], kb_id: Optional[str] = None + ): + super().__init__(version) + + self.chunks: Optional[List[str]] = payload.get("chunks") + + # Only set _solution if path params are provided (not None) + if kb_id is not None: + self._solution = { + "kb_id": kb_id, + } + + self._context: Optional[SearchContext] = None + + @property + def _proxy(self) -> "SearchContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SearchContext for this SearchInstance + """ + if self._context is None: + self._context = SearchContext( + self._version, + kb_id=self._solution["kb_id"], + ) + return self._context + + def create( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> "SearchInstance": + """ + Create the SearchInstance + + :param knowledge_search: + + :returns: The created SearchInstance + """ + return self._proxy.create( + knowledge_search=knowledge_search, + ) + + async def create_async( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> "SearchInstance": + """ + Asynchronous coroutine to create the SearchInstance + + :param knowledge_search: + + :returns: The created SearchInstance + """ + return await self._proxy.create_async( + knowledge_search=knowledge_search, + ) + + def create_with_http_info( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> ApiResponse: + """ + Create the SearchInstance with HTTP info + + :param knowledge_search: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + knowledge_search=knowledge_search, + ) + + async def create_with_http_info_async( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to create the SearchInstance with HTTP info + + :param knowledge_search: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + knowledge_search=knowledge_search, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SearchContext(InstanceContext): + + def __init__(self, version: Version, kb_id: str): + """ + Initialize the SearchContext + + :param version: Version that contains the resource + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + """ + super().__init__(version) + + # Path Solution + self._solution = { + "kb_id": kb_id, + } + self._uri = "/KnowledgeBases/{kb_id}/Search".format(**self._solution) + + def _create( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_search.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> SearchInstance: + """ + Create the SearchInstance + + :param knowledge_search: + + :returns: The created SearchInstance + """ + payload, _, _ = self._create(knowledge_search=knowledge_search) + return SearchInstance(self._version, payload, kb_id=self._solution["kb_id"]) + + def create_with_http_info( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> ApiResponse: + """ + Create the SearchInstance and return response metadata + + :param knowledge_search: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(knowledge_search=knowledge_search) + instance = SearchInstance(self._version, payload, kb_id=self._solution["kb_id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_search.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> SearchInstance: + """ + Asynchronous coroutine to create the SearchInstance + + :param knowledge_search: + + :returns: The created SearchInstance + """ + payload, _, _ = await self._create_async(knowledge_search=knowledge_search) + return SearchInstance(self._version, payload, kb_id=self._solution["kb_id"]) + + async def create_with_http_info_async( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to create the SearchInstance and return response metadata + + :param knowledge_search: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + knowledge_search=knowledge_search + ) + instance = SearchInstance(self._version, payload, kb_id=self._solution["kb_id"]) + return ApiResponse(data=instance, status_code=status_code, 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 SearchList(ListResource): + + class KnowledgeSearch(object): + """ + :ivar query: The query to search the knowledge source. + :ivar top: The top K results to return. + :ivar knowledge_ids: The list of knowledge IDs to search. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.query: Optional[str] = payload.get("query") + self.top: Optional[int] = payload.get("top") + self.knowledge_ids: Optional[List[str]] = payload.get("knowledgeIds") + + def to_dict(self): + return { + "query": self.query, + "top": self.top, + "knowledgeIds": self.knowledge_ids, + } + + def __init__(self, version: Version): + """ + Initialize the SearchList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, kb_id: str) -> SearchContext: + """ + Constructs a SearchContext + + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + """ + return SearchContext(self._version, kb_id=kb_id) + + def __call__(self, kb_id: str) -> SearchContext: + """ + Constructs a SearchContext + + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + """ + return SearchContext(self._version, kb_id=kb_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + 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..66ac1d0d6e 100644 --- a/twilio/rest/lookups/v1/phone_number.py +++ b/twilio/rest/lookups/v1/phone_number.py @@ -1,288 +1,420 @@ -# 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.api_response import ApiResponse 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): - """ """ - - def __init__(self, version): - """ - Initialize the PhoneNumberList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.lookups.v1.phone_number.PhoneNumberList - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberList - """ - super(PhoneNumberList, self).__init__(version) +class PhoneNumberInstance(InstanceResource): + """ + :ivar caller_name: The name of the phone number's owner. If `null`, that information was not available. + :ivar country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) for the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar national_format: The phone number, in national format. + :ivar carrier: The telecom company that provides the phone number. + :ivar add_ons: A JSON string with the results of the Add-ons you specified in the `add_ons` parameters. For the format of the object, see [Using Add-ons](https://www.twilio.com/docs/add-ons). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + phone_number: Optional[str] = None, + ): + super().__init__(version) + + self.caller_name: Optional[Dict[str, object]] = payload.get("caller_name") + self.country_code: Optional[str] = payload.get("country_code") + self.phone_number: Optional[str] = payload.get("phone_number") + self.national_format: Optional[str] = payload.get("national_format") + self.carrier: Optional[Dict[str, object]] = payload.get("carrier") + self.add_ons: Optional[Dict[str, object]] = payload.get("add_ons") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "phone_number": phone_number or self.phone_number, + } - # Path Solution - self._solution = {} + self._context: Optional[PhoneNumberContext] = None - def get(self, phone_number): + @property + def _proxy(self) -> "PhoneNumberContext": """ - Constructs a PhoneNumberContext - - :param phone_number: The phone number to fetch in E.164 format + 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.PhoneNumberContext - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberContext + :returns: PhoneNumberContext for this PhoneNumberInstance """ - return PhoneNumberContext(self._version, phone_number=phone_number, ) + if self._context is None: + self._context = PhoneNumberContext( + self._version, + phone_number=self._solution["phone_number"], + ) + return self._context - def __call__(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 - - :param phone_number: The phone number to fetch in E.164 format + Fetch the PhoneNumberInstance - :returns: twilio.rest.lookups.v1.phone_number.PhoneNumberContext - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberContext - """ - return PhoneNumberContext(self._version, phone_number=phone_number, ) + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. - def __repr__(self): + :returns: The fetched PhoneNumberInstance """ - Provide a friendly representation + return self._proxy.fetch( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) - :returns: Machine friendly representation - :rtype: str + 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": """ - return '' + Asynchronous coroutine to fetch the PhoneNumberInstance + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. -class PhoneNumberPage(Page): - """ """ + :returns: The fetched PhoneNumberInstance + """ + return await self._proxy.fetch_async( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) - def __init__(self, version, response, solution): + def fetch_with_http_info( + 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, + ) -> ApiResponse: """ - Initialize the PhoneNumberPage + Fetch the PhoneNumberInstance with HTTP info - :param Version version: Version that contains the resource - :param Response response: Response from the API + :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.PhoneNumberPage - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberPage + :returns: ApiResponse with instance, status code, and headers """ - super(PhoneNumberPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) - def get_instance(self, payload): + async def fetch_with_http_info_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, + ) -> ApiResponse: """ - Build an instance of PhoneNumberInstance + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info - :param dict payload: Payload response from the API + :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.PhoneNumberInstance - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers """ - return PhoneNumberInstance(self._version, payload, ) + return await self._proxy.fetch_with_http_info_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 PhoneNumberContext(InstanceContext): - """ """ - def __init__(self, version, phone_number): + def __init__(self, version: Version, phone_number: str): """ Initialize the PhoneNumberContext - :param Version version: Version that contains the resource - :param phone_number: The phone number to fetch in E.164 format - - :returns: twilio.rest.lookups.v1.phone_number.PhoneNumberContext - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberContext + :param version: Version that contains the resource + :param phone_number: The phone number to lookup in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. """ - super(PhoneNumberContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'phone_number': phone_number, } - self._uri = '/PhoneNumbers/{phone_number}'.format(**self._solution) + self._solution = { + "phone_number": phone_number, + } + self._uri = "/PhoneNumbers/{phone_number}".format(**self._solution) - def fetch(self, country_code=values.unset, type=values.unset, - add_ons=values.unset, add_ons_data=values.unset): + 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, + ) -> tuple: """ - 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 + Internal helper for fetch operation - :returns: The fetched PhoneNumberInstance - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ - 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, ) + params = values.of( + { + "CountryCode": country_code, + "Type": serialize.map(type, lambda e: e), + "AddOns": serialize.map(add_ons, lambda e: e), + } + ) - return PhoneNumberInstance(self._version, payload, phone_number=self._solution['phone_number'], ) + params.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) - def __repr__(self): - """ - Provide a friendly representation + 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["Accept"] = "application/json" + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) -class PhoneNumberInstance(InstanceResource): - """ """ + def fetch( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance - class Type(object): - LANDLINE = "landline" - MOBILE = "mobile" - VOIP = "voip" + :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. - def __init__(self, version, payload, phone_number=None): + :returns: The fetched PhoneNumberInstance """ - Initialize the PhoneNumberInstance + payload, _, _ = self._fetch( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) - :returns: twilio.rest.lookups.v1.phone_number.PhoneNumberInstance - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberInstance + def fetch_with_http_info( + 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, + ) -> ApiResponse: """ - super(PhoneNumberInstance, self).__init__(version) + Fetch the PhoneNumberInstance and return response metadata - # 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'), - } + :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. - # Context - self._context = None - self._solution = {'phone_number': phone_number or self._properties['phone_number'], } - - @property - def _proxy(self): + :returns: ApiResponse with instance, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, status_code, headers = self._fetch( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) + instance = PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: PhoneNumberContext for this PhoneNumberInstance - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberContext + 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, + ) -> tuple: """ - if self._context is None: - self._context = PhoneNumberContext(self._version, phone_number=self._solution['phone_number'], ) - return self._context + Internal async helper for fetch operation - @property - def caller_name(self): + Returns: + tuple: (payload, status_code, headers) """ - :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'] + params = values.of( + { + "CountryCode": country_code, + "Type": serialize.map(type, lambda e: e), + "AddOns": serialize.map(add_ons, lambda e: e), + } + ) - @property - def phone_number(self): - """ - :returns: The phone number in E.164 format - :rtype: unicode + params.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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: """ - return self._properties['phone_number'] + Asynchronous coroutine to fetch the PhoneNumberInstance - @property - def national_format(self): + :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 """ - :returns: The phone number, in national format - :rtype: unicode + payload, _, _ = await self._fetch_async( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['national_format'] + Asynchronous coroutine to fetch the PhoneNumberInstance and return response metadata - @property - def carrier(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The telecom company that provides the phone number - :rtype: dict + payload, status_code, headers = await self._fetch_async( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) + instance = PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - return self._properties['carrier'] + Provide a friendly representation - @property - def add_ons(self): + :returns: Machine friendly representation """ - :returns: A JSON string with the results of the Add-ons you specified - :rtype: dict + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['add_ons'] + Initialize the PhoneNumberList + + :param version: Version that contains the resource - @property - def url(self): """ - :returns: The absolute URL of the resource - :rtype: unicode + super().__init__(version) + + def get(self, phone_number: str) -> PhoneNumberContext: """ - return self._properties['url'] + Constructs a PhoneNumberContext - def fetch(self, country_code=values.unset, type=values.unset, - add_ons=values.unset, add_ons_data=values.unset): + :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. """ - Fetch the PhoneNumberInstance + return PhoneNumberContext(self._version, phone_number=phone_number) - :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 + def __call__(self, phone_number: str) -> PhoneNumberContext: + """ + 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..852f552540 --- /dev/null +++ b/twilio/rest/lookups/v2/__init__.py @@ -0,0 +1,75 @@ +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.bucket import BucketList +from twilio.rest.lookups.v2.lookup_override import LookupOverrideList +from twilio.rest.lookups.v2.phone_number import PhoneNumberList +from twilio.rest.lookups.v2.query import QueryList +from twilio.rest.lookups.v2.rate_limit import RateLimitList + + +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._bucket: Optional[BucketList] = None + self._lookup_overrides: Optional[LookupOverrideList] = None + self._phone_numbers: Optional[PhoneNumberList] = None + self._query: Optional[QueryList] = None + self._rate_limits: Optional[RateLimitList] = None + + @property + def bucket(self) -> BucketList: + if self._bucket is None: + self._bucket = BucketList(self) + return self._bucket + + @property + def lookup_overrides(self) -> LookupOverrideList: + if self._lookup_overrides is None: + self._lookup_overrides = LookupOverrideList(self) + return self._lookup_overrides + + @property + def phone_numbers(self) -> PhoneNumberList: + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList(self) + return self._phone_numbers + + @property + def query(self) -> QueryList: + if self._query is None: + self._query = QueryList(self) + return self._query + + @property + def rate_limits(self) -> RateLimitList: + if self._rate_limits is None: + self._rate_limits = RateLimitList(self) + return self._rate_limits + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/lookups/v2/bucket.py b/twilio/rest/lookups/v2/bucket.py new file mode 100644 index 0000000000..ce020fa8f3 --- /dev/null +++ b/twilio/rest/lookups/v2/bucket.py @@ -0,0 +1,621 @@ +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, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse +from twilio.base.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 BucketInstance(InstanceResource): + + class RateLimitRequest(object): + """ + :ivar limit: Limit of requests for the bucket + :ivar ttl: Time to live of the rule + """ + + def __init__(self, payload: Dict[str, Any]): + + self.limit: Optional[int] = payload.get("limit") + self.ttl: Optional[int] = payload.get("ttl") + + def to_dict(self): + return { + "limit": self.limit, + "ttl": self.ttl, + } + + """ + :ivar code: Twilio-specific error code + :ivar message: Error message + :ivar more_info: Link to Error Code References + :ivar status: HTTP response status code + :ivar field: Limit of requests for the bucket + :ivar limit: Limit of requests for the bucket + :ivar bucket: Name of the bucket + :ivar owner: Owner of the rule + :ivar ttl: Time to live of the rule + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + field: Optional[str] = None, + bucket: Optional[str] = None, + ): + super().__init__(version) + + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.more_info: Optional[str] = payload.get("more_info") + self.status: Optional[int] = payload.get("status") + self.field: Optional[str] = payload.get("field") + self.limit: Optional[int] = payload.get("limit") + self.bucket: Optional[str] = payload.get("bucket") + self.owner: Optional[str] = payload.get("owner") + self.ttl: Optional[int] = payload.get("ttl") + + self._solution = { + "field": field or self.field, + "bucket": bucket or self.bucket, + } + + self._context: Optional[BucketContext] = None + + @property + def _proxy(self) -> "BucketContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BucketContext for this BucketInstance + """ + if self._context is None: + self._context = BucketContext( + self._version, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BucketInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BucketInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "BucketInstance": + """ + Fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BucketInstance": + """ + Asynchronous coroutine to fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BucketInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BucketInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> "BucketInstance": + """ + Update the BucketInstance + + :param rate_limit_request: + + :returns: The updated BucketInstance + """ + return self._proxy.update( + rate_limit_request=rate_limit_request, + ) + + async def update_async( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> "BucketInstance": + """ + Asynchronous coroutine to update the BucketInstance + + :param rate_limit_request: + + :returns: The updated BucketInstance + """ + return await self._proxy.update_async( + rate_limit_request=rate_limit_request, + ) + + def update_with_http_info( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> ApiResponse: + """ + Update the BucketInstance with HTTP info + + :param rate_limit_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + rate_limit_request=rate_limit_request, + ) + + async def update_with_http_info_async( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BucketInstance with HTTP info + + :param rate_limit_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + rate_limit_request=rate_limit_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 BucketContext(InstanceContext): + + class RateLimitRequest(object): + """ + :ivar limit: Limit of requests for the bucket + :ivar ttl: Time to live of the rule + """ + + def __init__(self, payload: Dict[str, Any]): + + self.limit: Optional[int] = payload.get("limit") + self.ttl: Optional[int] = payload.get("ttl") + + def to_dict(self): + return { + "limit": self.limit, + "ttl": self.ttl, + } + + def __init__(self, version: Version, field: str, bucket: str): + """ + Initialize the BucketContext + + :param version: Version that contains the resource + :param field: field name + :param bucket: bucket name + """ + super().__init__(version) + + # Path Solution + self._solution = { + "field": field, + "bucket": bucket, + } + self._uri = "/RateLimits/Fields/{field}/Bucket/{bucket}".format( + **self._solution + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BucketInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BucketInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BucketInstance: + """ + Fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + payload, _, _ = self._fetch() + return BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BucketInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> BucketInstance: + """ + Asynchronous coroutine to fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + payload, _, _ = await self._fetch_async() + return BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BucketInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = rate_limit_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> BucketInstance: + """ + Update the BucketInstance + + :param rate_limit_request: + + :returns: The updated BucketInstance + """ + payload, _, _ = self._update(rate_limit_request=rate_limit_request) + return BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + + def update_with_http_info( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> ApiResponse: + """ + Update the BucketInstance and return response metadata + + :param rate_limit_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + rate_limit_request=rate_limit_request + ) + instance = BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = rate_limit_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> BucketInstance: + """ + Asynchronous coroutine to update the BucketInstance + + :param rate_limit_request: + + :returns: The updated BucketInstance + """ + payload, _, _ = await self._update_async(rate_limit_request=rate_limit_request) + return BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + + async def update_with_http_info_async( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BucketInstance and return response metadata + + :param rate_limit_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + rate_limit_request=rate_limit_request + ) + instance = BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 BucketList(ListResource): + + class RateLimitRequest(object): + """ + :ivar limit: Limit of requests for the bucket + :ivar ttl: Time to live of the rule + """ + + def __init__(self, payload: Dict[str, Any]): + + self.limit: Optional[int] = payload.get("limit") + self.ttl: Optional[int] = payload.get("ttl") + + def to_dict(self): + return { + "limit": self.limit, + "ttl": self.ttl, + } + + def __init__(self, version: Version): + """ + Initialize the BucketList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, field: str, bucket: str) -> BucketContext: + """ + Constructs a BucketContext + + :param field: field name + :param bucket: bucket name + """ + return BucketContext(self._version, field=field, bucket=bucket) + + def __call__(self, field: str, bucket: str) -> BucketContext: + """ + Constructs a BucketContext + + :param field: field name + :param bucket: bucket name + """ + return BucketContext(self._version, field=field, bucket=bucket) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/lookups/v2/lookup_override.py b/twilio/rest/lookups/v2/lookup_override.py new file mode 100644 index 0000000000..ea3cd6b389 --- /dev/null +++ b/twilio/rest/lookups/v2/lookup_override.py @@ -0,0 +1,828 @@ +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 datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.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 LookupOverrideInstance(InstanceResource): + + class OverridesRequest(object): + """ + :ivar line_type: The new line type to override the original line type + :ivar reason: The reason for the override + """ + + def __init__(self, payload: Dict[str, Any]): + + self.line_type: Optional["LookupOverrideInstance.str"] = payload.get( + "line_type" + ) + self.reason: Optional[str] = payload.get("reason") + + def to_dict(self): + return { + "line_type": self.line_type, + "reason": self.reason, + } + + """ + :ivar phone_number: The phone number for which the override was created + :ivar original_line_type: The original line type + :ivar overridden_line_type: The new line type after the override + :ivar override_reason: The reason for the override + :ivar override_timestamp: + :ivar overridden_by_account_sid: The Account SID for the user who made the override + :ivar code: Twilio-specific error code + :ivar message: Error message + :ivar more_info: Link to Error Code References + :ivar status: HTTP response status code + :ivar field: Limit of requests for the bucket + :ivar limit: Limit of requests for the bucket + :ivar bucket: Name of the bucket + :ivar owner: Owner of the rule + :ivar ttl: Time to live of the rule + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + field: Optional[str] = None, + phone_number: Optional[str] = None, + ): + super().__init__(version) + + self.phone_number: Optional[str] = payload.get("phone_number") + self.original_line_type: Optional["LookupOverrideInstance.str"] = payload.get( + "original_line_type" + ) + self.overridden_line_type: Optional["LookupOverrideInstance.str"] = payload.get( + "overridden_line_type" + ) + self.override_reason: Optional[str] = payload.get("override_reason") + self.override_timestamp: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("override_timestamp") + ) + self.overridden_by_account_sid: Optional[str] = payload.get( + "overridden_by_account_sid" + ) + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.more_info: Optional[str] = payload.get("more_info") + self.status: Optional[int] = payload.get("status") + self.field: Optional[str] = payload.get("field") + self.limit: Optional[int] = payload.get("limit") + self.bucket: Optional[str] = payload.get("bucket") + self.owner: Optional[str] = payload.get("owner") + self.ttl: Optional[int] = payload.get("ttl") + + self._solution = { + "field": field or self.field, + "phone_number": phone_number or self.phone_number, + } + + self._context: Optional[LookupOverrideContext] = None + + @property + def _proxy(self) -> "LookupOverrideContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: LookupOverrideContext for this LookupOverrideInstance + """ + if self._context is None: + self._context = LookupOverrideContext( + self._version, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + return self._context + + def create( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> "LookupOverrideInstance": + """ + Create the LookupOverrideInstance + + :param overrides_request: + + :returns: The created LookupOverrideInstance + """ + return self._proxy.create( + overrides_request=overrides_request, + ) + + async def create_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> "LookupOverrideInstance": + """ + Asynchronous coroutine to create the LookupOverrideInstance + + :param overrides_request: + + :returns: The created LookupOverrideInstance + """ + return await self._proxy.create_async( + overrides_request=overrides_request, + ) + + def create_with_http_info( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Create the LookupOverrideInstance with HTTP info + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + overrides_request=overrides_request, + ) + + async def create_with_http_info_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to create the LookupOverrideInstance with HTTP info + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + overrides_request=overrides_request, + ) + + def delete(self) -> bool: + """ + Deletes the LookupOverrideInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the LookupOverrideInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the LookupOverrideInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the LookupOverrideInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "LookupOverrideInstance": + """ + Fetch the LookupOverrideInstance + + + :returns: The fetched LookupOverrideInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "LookupOverrideInstance": + """ + Asynchronous coroutine to fetch the LookupOverrideInstance + + + :returns: The fetched LookupOverrideInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the LookupOverrideInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the LookupOverrideInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> "LookupOverrideInstance": + """ + Update the LookupOverrideInstance + + :param overrides_request: + + :returns: The updated LookupOverrideInstance + """ + return self._proxy.update( + overrides_request=overrides_request, + ) + + async def update_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> "LookupOverrideInstance": + """ + Asynchronous coroutine to update the LookupOverrideInstance + + :param overrides_request: + + :returns: The updated LookupOverrideInstance + """ + return await self._proxy.update_async( + overrides_request=overrides_request, + ) + + def update_with_http_info( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Update the LookupOverrideInstance with HTTP info + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + overrides_request=overrides_request, + ) + + async def update_with_http_info_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the LookupOverrideInstance with HTTP info + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + overrides_request=overrides_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 LookupOverrideContext(InstanceContext): + + class OverridesRequest(object): + """ + :ivar line_type: The new line type to override the original line type + :ivar reason: The reason for the override + """ + + def __init__(self, payload: Dict[str, Any]): + + self.line_type: Optional["LookupOverrideInstance.str"] = payload.get( + "line_type" + ) + self.reason: Optional[str] = payload.get("reason") + + def to_dict(self): + return { + "line_type": self.line_type, + "reason": self.reason, + } + + def __init__(self, version: Version, field: str, phone_number: str): + """ + Initialize the LookupOverrideContext + + :param version: Version that contains the resource + :param field: + :param phone_number: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "field": field, + "phone_number": phone_number, + } + self._uri = "/PhoneNumbers/{phone_number}/Overrides/{field}".format( + **self._solution + ) + + def _create( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = overrides_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> LookupOverrideInstance: + """ + Create the LookupOverrideInstance + + :param overrides_request: + + :returns: The created LookupOverrideInstance + """ + payload, _, _ = self._create(overrides_request=overrides_request) + return LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + + def create_with_http_info( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Create the LookupOverrideInstance and return response metadata + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + overrides_request=overrides_request + ) + instance = LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = overrides_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> LookupOverrideInstance: + """ + Asynchronous coroutine to create the LookupOverrideInstance + + :param overrides_request: + + :returns: The created LookupOverrideInstance + """ + payload, _, _ = await self._create_async(overrides_request=overrides_request) + return LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + + async def create_with_http_info_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to create the LookupOverrideInstance and return response metadata + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + overrides_request=overrides_request + ) + instance = LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the LookupOverrideInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the LookupOverrideInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the LookupOverrideInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the LookupOverrideInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> LookupOverrideInstance: + """ + Fetch the LookupOverrideInstance + + + :returns: The fetched LookupOverrideInstance + """ + payload, _, _ = self._fetch() + return LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the LookupOverrideInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> LookupOverrideInstance: + """ + Asynchronous coroutine to fetch the LookupOverrideInstance + + + :returns: The fetched LookupOverrideInstance + """ + payload, _, _ = await self._fetch_async() + return LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the LookupOverrideInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = overrides_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> LookupOverrideInstance: + """ + Update the LookupOverrideInstance + + :param overrides_request: + + :returns: The updated LookupOverrideInstance + """ + payload, _, _ = self._update(overrides_request=overrides_request) + return LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + + def update_with_http_info( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Update the LookupOverrideInstance and return response metadata + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + overrides_request=overrides_request + ) + instance = LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = overrides_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> LookupOverrideInstance: + """ + Asynchronous coroutine to update the LookupOverrideInstance + + :param overrides_request: + + :returns: The updated LookupOverrideInstance + """ + payload, _, _ = await self._update_async(overrides_request=overrides_request) + return LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + + async def update_with_http_info_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the LookupOverrideInstance and return response metadata + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + overrides_request=overrides_request + ) + instance = LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 LookupOverrideList(ListResource): + + class OverridesRequest(object): + """ + :ivar line_type: The new line type to override the original line type + :ivar reason: The reason for the override + """ + + def __init__(self, payload: Dict[str, Any]): + + self.line_type: Optional["LookupOverrideInstance.str"] = payload.get( + "line_type" + ) + self.reason: Optional[str] = payload.get("reason") + + def to_dict(self): + return { + "line_type": self.line_type, + "reason": self.reason, + } + + def __init__(self, version: Version): + """ + Initialize the LookupOverrideList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, field: str, phone_number: str) -> LookupOverrideContext: + """ + Constructs a LookupOverrideContext + + :param field: + :param phone_number: + """ + return LookupOverrideContext( + self._version, field=field, phone_number=phone_number + ) + + def __call__(self, field: str, phone_number: str) -> LookupOverrideContext: + """ + Constructs a LookupOverrideContext + + :param field: + :param phone_number: + """ + return LookupOverrideContext( + self._version, field=field, phone_number=phone_number + ) + + 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..2240351721 --- /dev/null +++ b/twilio/rest/lookups/v2/phone_number.py @@ -0,0 +1,761 @@ +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.api_response import ApiResponse +from twilio.base.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: + :ivar sim_swap: + :ivar call_forwarding: + :ivar line_type_intelligence: + :ivar line_status: + :ivar identity_match: + :ivar reassigned_number: + :ivar sms_pumping_risk: + :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[Enumstr]] = payload.get( + "validation_errors" + ) + self.caller_name: Optional[str] = payload.get("caller_name") + self.sim_swap: Optional[str] = payload.get("sim_swap") + self.call_forwarding: Optional[str] = payload.get("call_forwarding") + self.line_type_intelligence: Optional[str] = payload.get( + "line_type_intelligence" + ) + self.line_status: Optional[str] = payload.get("line_status") + self.identity_match: Optional[str] = payload.get("identity_match") + self.reassigned_number: Optional[str] = payload.get("reassigned_number") + self.sms_pumping_risk: Optional[str] = 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 fetch_with_http_info( + 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, + ) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = 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" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = self._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, + ) + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + def fetch_with_http_info( + 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, + ) -> ApiResponse: + """ + Fetch the PhoneNumberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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/lookups/v2/query.py b/twilio/rest/lookups/v2/query.py new file mode 100644 index 0000000000..1bb3ff6cc5 --- /dev/null +++ b/twilio/rest/lookups/v2/query.py @@ -0,0 +1,489 @@ +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 datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class QueryInstance(InstanceResource): + + class IdentityMatchParameters(object): + """ + :ivar first_name: + :ivar last_name: + :ivar address_line1: + :ivar address_line2: + :ivar city: + :ivar state: + :ivar postal_code: + :ivar address_country_code: + :ivar national_id: + :ivar date_of_birth: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.first_name: Optional[str] = payload.get("first_name") + self.last_name: Optional[str] = payload.get("last_name") + self.address_line1: Optional[str] = payload.get("address_line1") + self.address_line2: Optional[str] = payload.get("address_line2") + self.city: Optional[str] = payload.get("city") + self.state: Optional[str] = payload.get("state") + self.postal_code: Optional[str] = payload.get("postal_code") + self.address_country_code: Optional[str] = payload.get( + "address_country_code" + ) + self.national_id: Optional[str] = payload.get("national_id") + self.date_of_birth: Optional[str] = payload.get("date_of_birth") + + def to_dict(self): + return { + "first_name": self.first_name, + "last_name": self.last_name, + "address_line1": self.address_line1, + "address_line2": self.address_line2, + "city": self.city, + "state": self.state, + "postal_code": self.postal_code, + "address_country_code": self.address_country_code, + "national_id": self.national_id, + "date_of_birth": self.date_of_birth, + } + + class LastSimSwapInfo(object): + """ + :ivar last_sim_swap_date: + :ivar swapped_period: + :ivar swapped_in_period: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.last_sim_swap_date: Optional[datetime] = payload.get( + "last_sim_swap_date" + ) + self.swapped_period: Optional[str] = payload.get("swapped_period") + self.swapped_in_period: Optional[bool] = payload.get("swapped_in_period") + + def to_dict(self): + return { + "last_sim_swap_date": self.last_sim_swap_date, + "swapped_period": self.swapped_period, + "swapped_in_period": self.swapped_in_period, + } + + class LookupBatchRequest(object): + """ + :ivar correlation_id: Unique identifier used to match request with response + :ivar phone_number: + :ivar fields: + :ivar country_code: + :ivar identity_match: + :ivar reassigned_number: + :ivar sms_pumping_risk: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.correlation_id: Optional[str] = payload.get("correlation_id") + self.phone_number: Optional[str] = payload.get("phone_number") + self.fields: Optional[List[Enumstr]] = payload.get("fields") + self.country_code: Optional[str] = payload.get("country_code") + self.identity_match: Optional[QueryList.IdentityMatchParameters] = ( + payload.get("identity_match") + ) + self.reassigned_number: Optional[QueryList.ReassignedNumberParameters] = ( + payload.get("reassigned_number") + ) + self.sms_pumping_risk: Optional[QueryList.RiskParameters] = payload.get( + "sms_pumping_risk" + ) + + def to_dict(self): + return { + "correlation_id": self.correlation_id, + "phone_number": self.phone_number, + "fields": self.fields, + "country_code": self.country_code, + "identity_match": ( + self.identity_match.to_dict() + if self.identity_match is not None + else None + ), + "reassigned_number": ( + self.reassigned_number.to_dict() + if self.reassigned_number is not None + else None + ), + "sms_pumping_risk": ( + self.sms_pumping_risk.to_dict() + if self.sms_pumping_risk is not None + else None + ), + } + + class LookupRequest(object): + """ + :ivar phone_numbers: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_numbers: Optional[List[QueryList.LookupBatchRequest]] = ( + payload.get("phone_numbers") + ) + + def to_dict(self): + return { + "phone_numbers": ( + [phone_numbers.to_dict() for phone_numbers in self.phone_numbers] + if self.phone_numbers is not None + else None + ), + } + + class ReassignedNumberParameters(object): + """ + :ivar last_verified_date: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.last_verified_date: Optional[str] = payload.get("last_verified_date") + + def to_dict(self): + return { + "last_verified_date": self.last_verified_date, + } + + class RiskParameters(object): + """ + :ivar partner_sub_id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.partner_sub_id: Optional[str] = payload.get("partner_sub_id") + + def to_dict(self): + return { + "partner_sub_id": self.partner_sub_id, + } + + """ + :ivar phone_numbers: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.phone_numbers: Optional[List[str]] = payload.get("phone_numbers") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class QueryList(ListResource): + + class IdentityMatchParameters(object): + """ + :ivar first_name: + :ivar last_name: + :ivar address_line1: + :ivar address_line2: + :ivar city: + :ivar state: + :ivar postal_code: + :ivar address_country_code: + :ivar national_id: + :ivar date_of_birth: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.first_name: Optional[str] = payload.get("first_name") + self.last_name: Optional[str] = payload.get("last_name") + self.address_line1: Optional[str] = payload.get("address_line1") + self.address_line2: Optional[str] = payload.get("address_line2") + self.city: Optional[str] = payload.get("city") + self.state: Optional[str] = payload.get("state") + self.postal_code: Optional[str] = payload.get("postal_code") + self.address_country_code: Optional[str] = payload.get( + "address_country_code" + ) + self.national_id: Optional[str] = payload.get("national_id") + self.date_of_birth: Optional[str] = payload.get("date_of_birth") + + def to_dict(self): + return { + "first_name": self.first_name, + "last_name": self.last_name, + "address_line1": self.address_line1, + "address_line2": self.address_line2, + "city": self.city, + "state": self.state, + "postal_code": self.postal_code, + "address_country_code": self.address_country_code, + "national_id": self.national_id, + "date_of_birth": self.date_of_birth, + } + + class LastSimSwapInfo(object): + """ + :ivar last_sim_swap_date: + :ivar swapped_period: + :ivar swapped_in_period: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.last_sim_swap_date: Optional[datetime] = payload.get( + "last_sim_swap_date" + ) + self.swapped_period: Optional[str] = payload.get("swapped_period") + self.swapped_in_period: Optional[bool] = payload.get("swapped_in_period") + + def to_dict(self): + return { + "last_sim_swap_date": self.last_sim_swap_date, + "swapped_period": self.swapped_period, + "swapped_in_period": self.swapped_in_period, + } + + class LookupBatchRequest(object): + """ + :ivar correlation_id: Unique identifier used to match request with response + :ivar phone_number: + :ivar fields: + :ivar country_code: + :ivar identity_match: + :ivar reassigned_number: + :ivar sms_pumping_risk: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.correlation_id: Optional[str] = payload.get("correlation_id") + self.phone_number: Optional[str] = payload.get("phone_number") + self.fields: Optional[List[Enumstr]] = payload.get("fields") + self.country_code: Optional[str] = payload.get("country_code") + self.identity_match: Optional[QueryList.IdentityMatchParameters] = ( + payload.get("identity_match") + ) + self.reassigned_number: Optional[QueryList.ReassignedNumberParameters] = ( + payload.get("reassigned_number") + ) + self.sms_pumping_risk: Optional[QueryList.RiskParameters] = payload.get( + "sms_pumping_risk" + ) + + def to_dict(self): + return { + "correlation_id": self.correlation_id, + "phone_number": self.phone_number, + "fields": self.fields, + "country_code": self.country_code, + "identity_match": ( + self.identity_match.to_dict() + if self.identity_match is not None + else None + ), + "reassigned_number": ( + self.reassigned_number.to_dict() + if self.reassigned_number is not None + else None + ), + "sms_pumping_risk": ( + self.sms_pumping_risk.to_dict() + if self.sms_pumping_risk is not None + else None + ), + } + + class LookupRequest(object): + """ + :ivar phone_numbers: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_numbers: Optional[List[QueryList.LookupBatchRequest]] = ( + payload.get("phone_numbers") + ) + + def to_dict(self): + return { + "phone_numbers": ( + [phone_numbers.to_dict() for phone_numbers in self.phone_numbers] + if self.phone_numbers is not None + else None + ), + } + + class ReassignedNumberParameters(object): + """ + :ivar last_verified_date: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.last_verified_date: Optional[str] = payload.get("last_verified_date") + + def to_dict(self): + return { + "last_verified_date": self.last_verified_date, + } + + class RiskParameters(object): + """ + :ivar partner_sub_id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.partner_sub_id: Optional[str] = payload.get("partner_sub_id") + + def to_dict(self): + return { + "partner_sub_id": self.partner_sub_id, + } + + def __init__(self, version: Version): + """ + Initialize the QueryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/batch/query" + + def _create( + self, lookup_request: Union[LookupRequest, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = lookup_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, lookup_request: Union[LookupRequest, object] = values.unset + ) -> QueryInstance: + """ + Create the QueryInstance + + :param lookup_request: + + :returns: The created QueryInstance + """ + payload, _, _ = self._create(lookup_request=lookup_request) + return QueryInstance(self._version, payload) + + def create_with_http_info( + self, lookup_request: Union[LookupRequest, object] = values.unset + ) -> ApiResponse: + """ + Create the QueryInstance and return response metadata + + :param lookup_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(lookup_request=lookup_request) + instance = QueryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, lookup_request: Union[LookupRequest, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = lookup_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, lookup_request: Union[LookupRequest, object] = values.unset + ) -> QueryInstance: + """ + Asynchronously create the QueryInstance + + :param lookup_request: + + :returns: The created QueryInstance + """ + payload, _, _ = await self._create_async(lookup_request=lookup_request) + return QueryInstance(self._version, payload) + + async def create_with_http_info_async( + self, lookup_request: Union[LookupRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the QueryInstance and return response metadata + + :param lookup_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + lookup_request=lookup_request + ) + instance = QueryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/lookups/v2/rate_limit.py b/twilio/rest/lookups/v2/rate_limit.py new file mode 100644 index 0000000000..71d6ce17e3 --- /dev/null +++ b/twilio/rest/lookups/v2/rate_limit.py @@ -0,0 +1,157 @@ +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.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class RateLimitInstance(InstanceResource): + """ + :ivar rate_limits: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.rate_limits: Optional[List[str]] = payload.get("rate_limits") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class RateLimitList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RateLimitList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RateLimits" + + def _fetch(self, fields: Union[List[str], object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "Fields": fields, + } + ) + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers, params=params + ) + + def fetch( + self, fields: Union[List[str], object] = values.unset + ) -> RateLimitInstance: + """ + Fetch the RateLimitInstance + + :param fields: + :returns: The fetched RateLimitInstance + """ + payload, _, _ = self._fetch(fields=fields) + return RateLimitInstance(self._version, payload) + + def fetch_with_http_info( + self, fields: Union[List[str], object] = values.unset + ) -> ApiResponse: + """ + Fetch the RateLimitInstance and return response metadata + + :param fields: + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(fields=fields) + instance = RateLimitInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, fields: Union[List[str], object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "Fields": fields, + } + ) + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + async def fetch_async( + self, fields: Union[List[str], object] = values.unset + ) -> RateLimitInstance: + """ + Asynchronously fetch the RateLimitInstance + + :param fields: + :returns: The fetched RateLimitInstance + """ + payload, _, _ = await self._fetch_async(fields=fields) + return RateLimitInstance(self._version, payload) + + async def fetch_with_http_info_async( + self, fields: Union[List[str], object] = values.unset + ) -> ApiResponse: + """ + Asynchronously fetch the RateLimitInstance and return response metadata + + :param fields: + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(fields=fields) + instance = RateLimitInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..53ed2aeb1d --- /dev/null +++ b/twilio/rest/marketplace/v1/available_add_on/__init__.py @@ -0,0 +1,679 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AvailableAddOnInstance: + """ + Fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + payload, _, _ = self._fetch() + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AvailableAddOnInstance: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + payload, _, _ = await self._fetch_async() + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AvailableAddOnInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AvailableAddOnInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AvailableAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AvailableAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailableAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AvailableAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailableAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AvailableAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..14dcfed3af --- /dev/null +++ b/twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py @@ -0,0 +1,700 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AvailableAddOnExtensionInstance: + """ + Fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + payload, _, _ = self._fetch() + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnExtensionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AvailableAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + payload, _, _ = await self._fetch_async() + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AvailableAddOnExtensionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AvailableAddOnExtensionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AvailableAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AvailableAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution + ) + + async def 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, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailableAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailableAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..2553e78bf8 --- /dev/null +++ b/twilio/rest/marketplace/v1/installed_add_on/__init__.py @@ -0,0 +1,1191 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the InstalledAddOnInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + configuration=configuration, + unique_name=unique_name, + ) + + async def update_with_http_info_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InstalledAddOnInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InstalledAddOnInstance: + """ + Fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + payload, _, _ = self._fetch() + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> InstalledAddOnInstance: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + payload, _, _ = await self._fetch_async() + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + configuration=configuration, unique_name=unique_name + ) + return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the InstalledAddOnInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + configuration=configuration, unique_name=unique_name + ) + instance = InstalledAddOnInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + configuration=configuration, unique_name=unique_name + ) + return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + configuration=configuration, unique_name=unique_name + ) + instance = InstalledAddOnInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + return InstalledAddOnInstance(self._version, payload) + + def create_with_http_info( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the InstalledAddOnInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + instance = InstalledAddOnInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + return InstalledAddOnInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the InstalledAddOnInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + instance = InstalledAddOnInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InstalledAddOnInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InstalledAddOnInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InstalledAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InstalledAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InstalledAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InstalledAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..844c78e33f --- /dev/null +++ b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py @@ -0,0 +1,862 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info(self, enabled: bool) -> ApiResponse: + """ + Update the InstalledAddOnExtensionInstance with HTTP info + + :param enabled: Whether the Extension should be invoked. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + enabled=enabled, + ) + + async def update_with_http_info_async(self, enabled: bool) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance with HTTP info + + :param enabled: Whether the Extension should be invoked. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InstalledAddOnExtensionInstance: + """ + Fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + payload, _, _ = self._fetch() + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnExtensionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> InstalledAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + payload, _, _ = await self._fetch_async() + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, enabled: bool) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, enabled: bool) -> InstalledAddOnExtensionInstance: + """ + Update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + payload, _, _ = self._update(enabled=enabled) + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info(self, enabled: bool) -> ApiResponse: + """ + Update the InstalledAddOnExtensionInstance and return response metadata + + :param enabled: Whether the Extension should be invoked. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(enabled=enabled) + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, enabled: bool) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(enabled=enabled) + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async(self, enabled: bool) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance and return response metadata + + :param enabled: Whether the Extension should be invoked. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(enabled=enabled) + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InstalledAddOnExtensionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InstalledAddOnExtensionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InstalledAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InstalledAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution + ) + + async def 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, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..9a2a66844b --- /dev/null +++ b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py @@ -0,0 +1,303 @@ +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.api_response import ApiResponse + +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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + marketplace_v1_installed_add_on_installed_add_on_usage=marketplace_v1_installed_add_on_installed_add_on_usage + ) + return InstalledAddOnUsageInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) + + def create_with_http_info( + self, + marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, + ) -> ApiResponse: + """ + Create the InstalledAddOnUsageInstance and return response metadata + + :param marketplace_v1_installed_add_on_installed_add_on_usage: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + marketplace_v1_installed_add_on_installed_add_on_usage=marketplace_v1_installed_add_on_installed_add_on_usage + ) + instance = InstalledAddOnUsageInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + marketplace_v1_installed_add_on_installed_add_on_usage=marketplace_v1_installed_add_on_installed_add_on_usage + ) + return InstalledAddOnUsageInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) + + async def create_with_http_info_async( + self, + marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, + ) -> ApiResponse: + """ + Asynchronously create the InstalledAddOnUsageInstance and return response metadata + + :param marketplace_v1_installed_add_on_installed_add_on_usage: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + marketplace_v1_installed_add_on_installed_add_on_usage=marketplace_v1_installed_add_on_installed_add_on_usage + ) + instance = InstalledAddOnUsageInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..90a6cbb99a --- /dev/null +++ b/twilio/rest/marketplace/v1/module_data.py @@ -0,0 +1,283 @@ +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.api_response import ApiResponse + +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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + module_info=module_info, configuration=configuration + ) + return ModuleDataInstance(self._version, payload) + + def create_with_http_info( + self, + module_info: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ModuleDataInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + module_info=module_info, configuration=configuration + ) + instance = ModuleDataInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + module_info: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + module_info=module_info, configuration=configuration + ) + return ModuleDataInstance(self._version, payload) + + async def create_with_http_info_async( + self, + module_info: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ModuleDataInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + module_info=module_info, configuration=configuration + ) + instance = ModuleDataInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ModuleDataInstance: + """ + Fetch the ModuleDataInstance + + + :returns: The fetched ModuleDataInstance + """ + payload, _, _ = self._fetch() + return ModuleDataInstance(self._version, payload) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ModuleDataInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ModuleDataInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ModuleDataInstance: + """ + Asynchronously fetch the ModuleDataInstance + + + :returns: The fetched ModuleDataInstance + """ + payload, _, _ = await self._fetch_async() + return ModuleDataInstance(self._version, payload) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously fetch the ModuleDataInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ModuleDataInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..6ac9e02d46 --- /dev/null +++ b/twilio/rest/marketplace/v1/module_data_management.py @@ -0,0 +1,625 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ModuleDataManagementInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ModuleDataManagementInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ModuleDataManagementInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ModuleDataManagementInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ModuleDataManagementInstance: + """ + Fetch the ModuleDataManagementInstance + + + :returns: The fetched ModuleDataManagementInstance + """ + payload, _, _ = self._fetch() + return ModuleDataManagementInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ModuleDataManagementInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ModuleDataManagementInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ModuleDataManagementInstance: + """ + Asynchronous coroutine to fetch the ModuleDataManagementInstance + + + :returns: The fetched ModuleDataManagementInstance + """ + payload, _, _ = await self._fetch_async() + return ModuleDataManagementInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ModuleDataManagementInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ModuleDataManagementInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) + return ModuleDataManagementInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ModuleDataManagementInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) + instance = ModuleDataManagementInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) + return ModuleDataManagementInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ModuleDataManagementInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) + instance = ModuleDataManagementInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..1234b45c6f --- /dev/null +++ b/twilio/rest/marketplace/v1/referral_conversion.py @@ -0,0 +1,200 @@ +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.api_response import ApiResponse + +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 + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_referral_conversion_request: CreateReferralConversionRequest + ) -> ReferralConversionInstance: + """ + Create the ReferralConversionInstance + + :param create_referral_conversion_request: + + :returns: The created ReferralConversionInstance + """ + payload, _, _ = self._create( + create_referral_conversion_request=create_referral_conversion_request + ) + return ReferralConversionInstance(self._version, payload) + + def create_with_http_info( + self, create_referral_conversion_request: CreateReferralConversionRequest + ) -> ApiResponse: + """ + Create the ReferralConversionInstance and return response metadata + + :param create_referral_conversion_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_referral_conversion_request=create_referral_conversion_request + ) + instance = ReferralConversionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_referral_conversion_request: CreateReferralConversionRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_referral_conversion_request: CreateReferralConversionRequest + ) -> ReferralConversionInstance: + """ + Asynchronously create the ReferralConversionInstance + + :param create_referral_conversion_request: + + :returns: The created ReferralConversionInstance + """ + payload, _, _ = await self._create_async( + create_referral_conversion_request=create_referral_conversion_request + ) + return ReferralConversionInstance(self._version, payload) + + async def create_with_http_info_async( + self, create_referral_conversion_request: CreateReferralConversionRequest + ) -> ApiResponse: + """ + Asynchronously create the ReferralConversionInstance and return response metadata + + :param create_referral_conversion_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_referral_conversion_request=create_referral_conversion_request + ) + instance = ReferralConversionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/MemoryBase.py b/twilio/rest/memory/MemoryBase.py new file mode 100644 index 0000000000..1ced0e0da8 --- /dev/null +++ b/twilio/rest/memory/MemoryBase.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.memory.v1 import V1 + + +class MemoryBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Memory Domain + + :returns: Domain for Memory + """ + super().__init__(twilio, "https://memory.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Memory + """ + 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/memory/__init__.py b/twilio/rest/memory/__init__.py new file mode 100644 index 0000000000..3a4eec065e --- /dev/null +++ b/twilio/rest/memory/__init__.py @@ -0,0 +1,5 @@ +from twilio.rest.memory.MemoryBase import MemoryBase + + +class Memory(MemoryBase): + pass diff --git a/twilio/rest/memory/v1/__init__.py b/twilio/rest/memory/v1/__init__.py new file mode 100644 index 0000000000..9aa8e05f55 --- /dev/null +++ b/twilio/rest/memory/v1/__init__.py @@ -0,0 +1,285 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This 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.memory.v1.bulk import BulkList +from twilio.rest.memory.v1.conversation_summary import ConversationSummaryList +from twilio.rest.memory.v1.data_mapping import DataMappingList +from twilio.rest.memory.v1.event import EventList +from twilio.rest.memory.v1.identifier import IdentifierList +from twilio.rest.memory.v1.identity_resolution_setting import ( + IdentityResolutionSettingList, +) +from twilio.rest.memory.v1.import_ import ImportList +from twilio.rest.memory.v1.lookup import LookupList +from twilio.rest.memory.v1.observation import ObservationList +from twilio.rest.memory.v1.operation import OperationList +from twilio.rest.memory.v1.profile import ProfileList +from twilio.rest.memory.v1.recall import RecallList +from twilio.rest.memory.v1.revision import RevisionList +from twilio.rest.memory.v1.store import StoreList +from twilio.rest.memory.v1.trait import TraitList +from twilio.rest.memory.v1.trait_group import TraitGroupList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Memory + + :param domain: The Twilio.memory domain + """ + super().__init__(domain, "v1") + self._operations: Optional[OperationList] = None + self._stores: Optional[StoreList] = None + + def bulk(self, store_id: str, bulk_id: str = None): + """ + Access the BulkList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param bulk_id: Optional instance ID to directly access BulkContext + :returns: BulkList instance if bulk_id is None, otherwise BulkContext + """ + list_instance = BulkList(self) + return list_instance(store_id) + + def conversation_summaries( + self, store_id: str, profile_id: str, conversation_summary_id: str = None + ): + """ + Access the ConversationSummaryList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + :param conversation_summary_id: Optional instance ID to directly access ConversationSummaryContext + :returns: ConversationSummaryList instance if conversation_summary_id is None, otherwise ConversationSummaryContext + """ + list_instance = ConversationSummaryList(self, store_id, profile_id) + if conversation_summary_id is not None: + return list_instance(conversation_summary_id) + return list_instance + + def data_mappings(self, store_id: str, data_mapping_id: str = None): + """ + Access the DataMappingList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param data_mapping_id: Optional instance ID to directly access DataMappingContext + :returns: DataMappingList instance if data_mapping_id is None, otherwise DataMappingContext + """ + list_instance = DataMappingList(self, store_id) + if data_mapping_id is not None: + return list_instance(data_mapping_id) + return list_instance + + def events(self, store_id: str, profile_id: str, event_id: str = None): + """ + Access the EventList resource + + :param store_id: The storeId identifier + + :param profile_id: The profileId identifier + + :param event_id: Optional instance ID to directly access EventContext + :returns: EventList instance if event_id is None, otherwise EventContext + """ + list_instance = EventList(self, store_id, profile_id) + if event_id is not None: + return list_instance(event_id) + return list_instance + + def identifiers(self, store_id: str, profile_id: str, identifier_id: str = None): + """ + Access the IdentifierList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + :param identifier_id: Optional instance ID to directly access IdentifierContext + :returns: IdentifierList instance if identifier_id is None, otherwise IdentifierContext + """ + list_instance = IdentifierList(self, store_id, profile_id) + if identifier_id is not None: + return list_instance(identifier_id) + return list_instance + + def identity_resolution_settings( + self, store_id: str, identity_resolution_setting_id: str = None + ): + """ + Access the IdentityResolutionSettingList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param identity_resolution_setting_id: Optional instance ID to directly access IdentityResolutionSettingContext + :returns: IdentityResolutionSettingList instance if identity_resolution_setting_id is None, otherwise IdentityResolutionSettingContext + """ + list_instance = IdentityResolutionSettingList(self) + return list_instance(store_id) + + def imports(self, store_id: str, import_id: str = None): + """ + Access the ImportList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param import_id: Optional instance ID to directly access ImportContext + :returns: ImportList instance if import_id is None, otherwise ImportContext + """ + list_instance = ImportList(self, store_id) + if import_id is not None: + return list_instance(import_id) + return list_instance + + def lookup(self, store_id: str, lookup_id: str = None): + """ + Access the LookupList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param lookup_id: Optional instance ID to directly access LookupContext + :returns: LookupList instance if lookup_id is None, otherwise LookupContext + """ + list_instance = LookupList(self, store_id) + if lookup_id is not None: + return list_instance(lookup_id) + return list_instance + + def observations(self, store_id: str, profile_id: str, observation_id: str = None): + """ + Access the ObservationList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + :param observation_id: Optional instance ID to directly access ObservationContext + :returns: ObservationList instance if observation_id is None, otherwise ObservationContext + """ + list_instance = ObservationList(self, store_id, profile_id) + if observation_id is not None: + return list_instance(observation_id) + return list_instance + + @property + def operations(self) -> OperationList: + if self._operations is None: + self._operations = OperationList(self) + return self._operations + + def profiles(self, store_id: str, profile_id: str = None): + """ + Access the ProfileList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param profile_id: Optional instance ID to directly access ProfileContext + :returns: ProfileList instance if profile_id is None, otherwise ProfileContext + """ + list_instance = ProfileList(self, store_id) + if profile_id is not None: + return list_instance(profile_id) + return list_instance + + def recall(self, store_id: str, profile_id: str, recall_id: str = None): + """ + Access the RecallList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + :param recall_id: Optional instance ID to directly access RecallContext + :returns: RecallList instance if recall_id is None, otherwise RecallContext + """ + list_instance = RecallList(self, store_id, profile_id) + if recall_id is not None: + return list_instance(recall_id) + return list_instance + + def revisions( + self, + store_id: str, + profile_id: str, + observation_id: str, + revision_id: str = None, + ): + """ + Access the RevisionList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + :param observation_id: The observation ID. + + :param revision_id: Optional instance ID to directly access RevisionContext + :returns: RevisionList instance if revision_id is None, otherwise RevisionContext + """ + list_instance = RevisionList(self, store_id, profile_id, observation_id) + if revision_id is not None: + return list_instance(revision_id) + return list_instance + + @property + def stores(self) -> StoreList: + if self._stores is None: + self._stores = StoreList(self) + return self._stores + + def traits(self, store_id: str, profile_id: str, trait_id: str = None): + """ + Access the TraitList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + :param trait_id: Optional instance ID to directly access TraitContext + :returns: TraitList instance if trait_id is None, otherwise TraitContext + """ + list_instance = TraitList(self, store_id, profile_id) + if trait_id is not None: + return list_instance(trait_id) + return list_instance + + def trait_groups(self, store_id: str, trait_group_id: str = None): + """ + Access the TraitGroupList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param trait_group_id: Optional instance ID to directly access TraitGroupContext + :returns: TraitGroupList instance if trait_group_id is None, otherwise TraitGroupContext + """ + list_instance = TraitGroupList(self, store_id) + if trait_group_id is not None: + return list_instance(trait_group_id) + return list_instance + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/bulk.py b/twilio/rest/memory/v1/bulk.py new file mode 100644 index 0000000000..4112d066f6 --- /dev/null +++ b/twilio/rest/memory/v1/bulk.py @@ -0,0 +1,327 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse +from twilio.base.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 BulkInstance(InstanceResource): + """ + :ivar message: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], store_id: Optional[str] = None + ): + super().__init__(version) + + self.message: Optional[str] = payload.get("message") + + # Only set _solution if path params are provided (not None) + if store_id is not None: + self._solution = { + "store_id": store_id, + } + + self._context: Optional[BulkContext] = None + + @property + def _proxy(self) -> "BulkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BulkContext for this BulkInstance + """ + if self._context is None: + self._context = BulkContext( + self._version, + store_id=self._solution["store_id"], + ) + return self._context + + def update( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> "BulkInstance": + """ + Update the BulkInstance + + :param update_profiles_bulk_request: + + :returns: The updated BulkInstance + """ + return self._proxy.update( + update_profiles_bulk_request=update_profiles_bulk_request, + ) + + async def update_async( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> "BulkInstance": + """ + Asynchronous coroutine to update the BulkInstance + + :param update_profiles_bulk_request: + + :returns: The updated BulkInstance + """ + return await self._proxy.update_async( + update_profiles_bulk_request=update_profiles_bulk_request, + ) + + def update_with_http_info( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> ApiResponse: + """ + Update the BulkInstance with HTTP info + + :param update_profiles_bulk_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + update_profiles_bulk_request=update_profiles_bulk_request, + ) + + async def update_with_http_info_async( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BulkInstance with HTTP info + + :param update_profiles_bulk_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + update_profiles_bulk_request=update_profiles_bulk_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 BulkContext(InstanceContext): + + def __init__(self, version: Version, store_id: str): + """ + Initialize the BulkContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/Stores/{store_id}/Profiles/Bulk".format(**self._solution) + + def _update(self, update_profiles_bulk_request: UpdateProfilesBulkRequest) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_profiles_bulk_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> BulkInstance: + """ + Update the BulkInstance + + :param update_profiles_bulk_request: + + :returns: The updated BulkInstance + """ + payload, _, _ = self._update( + update_profiles_bulk_request=update_profiles_bulk_request + ) + return BulkInstance(self._version, payload, store_id=self._solution["store_id"]) + + def update_with_http_info( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> ApiResponse: + """ + Update the BulkInstance and return response metadata + + :param update_profiles_bulk_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + update_profiles_bulk_request=update_profiles_bulk_request + ) + instance = BulkInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_profiles_bulk_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> BulkInstance: + """ + Asynchronous coroutine to update the BulkInstance + + :param update_profiles_bulk_request: + + :returns: The updated BulkInstance + """ + payload, _, _ = await self._update_async( + update_profiles_bulk_request=update_profiles_bulk_request + ) + return BulkInstance(self._version, payload, store_id=self._solution["store_id"]) + + async def update_with_http_info_async( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BulkInstance and return response metadata + + :param update_profiles_bulk_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + update_profiles_bulk_request=update_profiles_bulk_request + ) + instance = BulkInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 BulkList(ListResource): + + class ProfileData(object): + """ + :ivar traits: Multiple trait groups. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.traits: Optional[Dict[str, Dict[str, object]]] = payload.get("traits") + + def to_dict(self): + return { + "traits": self.traits, + } + + class UpdateProfilesBulkRequest(object): + """ + :ivar profiles: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.profiles: Optional[List[BulkList.ProfileData]] = payload.get( + "profiles" + ) + + def to_dict(self): + return { + "profiles": ( + [profiles.to_dict() for profiles in self.profiles] + if self.profiles is not None + else None + ), + } + + def __init__(self, version: Version): + """ + Initialize the BulkList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, store_id: str) -> BulkContext: + """ + Constructs a BulkContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return BulkContext(self._version, store_id=store_id) + + def __call__(self, store_id: str) -> BulkContext: + """ + Constructs a BulkContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return BulkContext(self._version, store_id=store_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/conversation_summary.py b/twilio/rest/memory/v1/conversation_summary.py new file mode 100644 index 0000000000..adada4fabd --- /dev/null +++ b/twilio/rest/memory/v1/conversation_summary.py @@ -0,0 +1,1295 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ConversationSummaryInstance(InstanceResource): + """ + :ivar source: The source system that generated the summary. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :ivar content: The main content of the summary. + :ivar occurred_at: The timestamp when the summary was originally created. + :ivar conversation_id: A unique identifier for the conversation using Twilio Type ID (TTID) format. + :ivar id: A unique identifier for the summary using Twilio Type ID (TTID) format. + :ivar created_at: The timestamp when the summary was created. + :ivar updated_at: The timestamp when the summary was last updated. + :ivar message: + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: str, + profile_id: str, + summary_id: Optional[str] = None, + ): + super().__init__(version) + + self.source: Optional[str] = payload.get("source") + self.content: Optional[str] = payload.get("content") + self.occurred_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("occurredAt") + ) + self.conversation_id: Optional[str] = payload.get("conversationId") + self.id: Optional[str] = payload.get("id") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.message: Optional[str] = payload.get("message") + + # Only set _solution if path params are provided (not None) + if store_id is not None or profile_id is not None or summary_id is not None: + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "summary_id": summary_id, + } + + self._context: Optional[ConversationSummaryContext] = None + + @property + def _proxy(self) -> "ConversationSummaryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConversationSummaryContext for this ConversationSummaryInstance + """ + if self._context is None: + self._context = ConversationSummaryContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ConversationSummaryInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConversationSummaryInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConversationSummaryInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationSummaryInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "ConversationSummaryInstance": + """ + Fetch the ConversationSummaryInstance + + + :returns: The fetched ConversationSummaryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConversationSummaryInstance": + """ + Asynchronous coroutine to fetch the ConversationSummaryInstance + + + :returns: The fetched ConversationSummaryInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationSummaryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationSummaryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def patch( + self, summary_core_patch: SummaryCorePatch + ) -> "ConversationSummaryInstance": + """ + Patch the ConversationSummaryInstance + + :param summary_core_patch: + + :returns: The patched ConversationSummaryInstance + """ + return self._proxy.patch( + summary_core_patch=summary_core_patch, + ) + + async def patch_async( + self, summary_core_patch: SummaryCorePatch + ) -> "ConversationSummaryInstance": + """ + Asynchronous coroutine to patch the ConversationSummaryInstance + + :param summary_core_patch: + + :returns: The patched ConversationSummaryInstance + """ + return await self._proxy.patch_async( + summary_core_patch=summary_core_patch, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConversationSummaryContext(InstanceContext): + + def __init__( + self, version: Version, store_id: str, profile_id: str, summary_id: str + ): + """ + Initialize the ConversationSummaryContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + :param summary_id: The summary ID. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "summary_id": summary_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/ConversationSummaries/{summary_id}".format( + **self._solution + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ConversationSummaryInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConversationSummaryInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConversationSummaryInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationSummaryInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConversationSummaryInstance: + """ + Fetch the ConversationSummaryInstance + + + :returns: The fetched ConversationSummaryInstance + """ + payload, _, _ = self._fetch() + return ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationSummaryInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConversationSummaryInstance: + """ + Asynchronous coroutine to fetch the ConversationSummaryInstance + + + :returns: The fetched ConversationSummaryInstance + """ + payload, _, _ = await self._fetch_async() + return ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationSummaryInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch(self, summary_core_patch: SummaryCorePatch) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = summary_core_patch.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch( + self, summary_core_patch: SummaryCorePatch + ) -> ConversationSummaryInstance: + """ + Patch the ConversationSummaryInstance + + :param summary_core_patch: + + :returns: The patched ConversationSummaryInstance + """ + payload, _, _ = self._patch(summary_core_patch=summary_core_patch) + return ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + + def patch_with_http_info(self, summary_core_patch: SummaryCorePatch) -> ApiResponse: + """ + Patch the ConversationSummaryInstance and return response metadata + + :param summary_core_patch: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch( + summary_core_patch=summary_core_patch + ) + instance = ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async(self, summary_core_patch: SummaryCorePatch) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = summary_core_patch.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async( + self, summary_core_patch: SummaryCorePatch + ) -> ConversationSummaryInstance: + """ + Asynchronous coroutine to patch the ConversationSummaryInstance + + :param summary_core_patch: + + :returns: The patched ConversationSummaryInstance + """ + payload, _, _ = await self._patch_async(summary_core_patch=summary_core_patch) + return ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + + async def patch_with_http_info_async( + self, summary_core_patch: SummaryCorePatch + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the ConversationSummaryInstance and return response metadata + + :param summary_core_patch: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + summary_core_patch=summary_core_patch + ) + instance = ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 ConversationSummaryPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ConversationSummaryInstance: + """ + Build an instance of ConversationSummaryInstance + + :param payload: Payload response from the API + """ + + return ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConversationSummaryList(ListResource): + + class CreateSummariesRequest(object): + """ + :ivar summaries: Array of summaries to create in a single batch operation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.summaries: Optional[List[ConversationSummaryList.SummaryCore]] = ( + payload.get("summaries") + ) + + def to_dict(self): + return { + "summaries": ( + [summaries.to_dict() for summaries in self.summaries] + if self.summaries is not None + else None + ), + } + + class SummaryCore(object): + """ + :ivar source: The source system that generated the summary. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :ivar content: The main content of the summary. + :ivar occurred_at: The timestamp when the summary was originally created. + :ivar conversation_id: A unique identifier for the conversation using Twilio Type ID (TTID) format. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.source: Optional[str] = payload.get("source") + self.content: Optional[str] = payload.get("content") + self.occurred_at: Optional[datetime] = payload.get("occurredAt") + self.conversation_id: Optional[str] = payload.get("conversationId") + + def to_dict(self): + return { + "source": self.source, + "content": self.content, + "occurredAt": self.occurred_at, + "conversationId": self.conversation_id, + } + + class SummaryCorePatch(object): + """ + :ivar source: The source system that generated the summary. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :ivar content: The main content of the summary. + :ivar occurred_at: The timestamp when the summary was originally created. If not provided, defaults to the time the summary was received. + :ivar conversation_id: A unique identifier for the conversation using Twilio Type ID (TTID) format. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.source: Optional[str] = payload.get("source") + self.content: Optional[str] = payload.get("content") + self.occurred_at: Optional[datetime] = payload.get("occurredAt") + self.conversation_id: Optional[str] = payload.get("conversationId") + + def to_dict(self): + return { + "source": self.source, + "content": self.content, + "occurredAt": self.occurred_at, + "conversationId": self.conversation_id, + } + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the ConversationSummaryList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + self._uri = ( + "/Stores/{store_id}/Profiles/{profile_id}/ConversationSummaries".format( + **self._solution + ) + ) + + def _create( + self, + create_summaries_request: CreateSummariesRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_summaries_request.to_dict() + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Encoding": content_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + create_summaries_request: CreateSummariesRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ConversationSummaryInstance: + """ + Create the ConversationSummaryInstance + + :param create_summaries_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: The created ConversationSummaryInstance + """ + payload, _, _ = self._create( + create_summaries_request=create_summaries_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + return ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def create_with_http_info( + self, + create_summaries_request: CreateSummariesRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ConversationSummaryInstance and return response metadata + + :param create_summaries_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_summaries_request=create_summaries_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + instance = ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + create_summaries_request: CreateSummariesRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_summaries_request.to_dict() + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Encoding": content_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + create_summaries_request: CreateSummariesRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ConversationSummaryInstance: + """ + Asynchronously create the ConversationSummaryInstance + + :param create_summaries_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: The created ConversationSummaryInstance + """ + payload, _, _ = await self._create_async( + create_summaries_request=create_summaries_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + return ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + async def create_with_http_info_async( + self, + create_summaries_request: CreateSummariesRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ConversationSummaryInstance and return response metadata + + :param create_summaries_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_summaries_request=create_summaries_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + instance = ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConversationSummaryInstance]: + """ + Streams ConversationSummaryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConversationSummaryInstance]: + """ + Asynchronously streams ConversationSummaryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConversationSummaryInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConversationSummaryInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationSummaryInstance]: + """ + Lists ConversationSummaryInstance 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: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationSummaryInstance]: + """ + Asynchronously lists ConversationSummaryInstance 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: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConversationSummaryInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConversationSummaryInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + ) -> ConversationSummaryPage: + """ + Retrieve a single page of ConversationSummaryInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :returns: Page of ConversationSummaryInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "Accept-Encoding": accept_encoding, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationSummaryPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + ) -> ConversationSummaryPage: + """ + Asynchronously retrieve a single page of ConversationSummaryInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :returns: Page of ConversationSummaryInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "Accept-Encoding": accept_encoding, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationSummaryPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + accept_encoding: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConversationSummaryPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "Accept-Encoding": accept_encoding, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConversationSummaryPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + accept_encoding: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConversationSummaryPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "Accept-Encoding": accept_encoding, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConversationSummaryPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ConversationSummaryPage: + """ + Retrieve a specific page of ConversationSummaryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationSummaryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConversationSummaryPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ConversationSummaryPage: + """ + Asynchronously retrieve a specific page of ConversationSummaryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationSummaryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConversationSummaryPage(self._version, response, solution=self._solution) + + def get(self, summary_id: str) -> ConversationSummaryContext: + """ + Constructs a ConversationSummaryContext + + :param summary_id: The summary ID. + """ + return ConversationSummaryContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=summary_id, + ) + + def __call__(self, summary_id: str) -> ConversationSummaryContext: + """ + Constructs a ConversationSummaryContext + + :param summary_id: The summary ID. + """ + return ConversationSummaryContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=summary_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/data_mapping.py b/twilio/rest/memory/v1/data_mapping.py new file mode 100644 index 0000000000..4a055daed3 --- /dev/null +++ b/twilio/rest/memory/v1/data_mapping.py @@ -0,0 +1,1341 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class DataMappingInstance(InstanceResource): + + class DataMappingType(object): + DATASET = "DATASET" + + """ + :ivar message: + :ivar status_url: URI to check operation status. + :ivar display_name: Name of the data mapping. + :ivar description: A human readable description of this resource, up to 512 characters. + :ivar is_enabled: Flag indicating whether the data mapping is active. When true, data will be ingested and mapped according to the configuration. When false, the data mapping will be inactive and no data will be ingested into the Memory Store. + :ivar mapping_to: + :ivar mapping_from: + :ivar id: The unique identifier for the data mapping. + :ivar created_at: The ISO 8601 timestamp when the data mapping was created. + :ivar updated_at: The ISO 8601 timestamp when the data mapping was last updated. + :ivar version: The current version number of the DataMapping. Incremented on each successful update. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: str, + data_mapping_id: Optional[str] = None, + ): + super().__init__(version) + + self.message: Optional[str] = payload.get("message") + self.status_url: Optional[str] = payload.get("statusUrl") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.is_enabled: Optional[bool] = payload.get("isEnabled") + self.mapping_to: Optional[DataMappingToTraits] = payload.get("mappingTo") + self.mapping_from: Optional[DataMappingFromDataSet] = payload.get("mappingFrom") + self.id: Optional[str] = payload.get("id") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.version: Optional[int] = deserialize.integer(payload.get("version")) + + # Only set _solution if path params are provided (not None) + if store_id is not None or data_mapping_id is not None: + self._solution = { + "store_id": store_id, + "data_mapping_id": data_mapping_id, + } + + self._context: Optional[DataMappingContext] = None + + @property + def _proxy(self) -> "DataMappingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DataMappingContext for this DataMappingInstance + """ + if self._context is None: + self._context = DataMappingContext( + self._version, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DataMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DataMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DataMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DataMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "DataMappingInstance": + """ + Fetch the DataMappingInstance + + + :returns: The fetched DataMappingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DataMappingInstance": + """ + Asynchronous coroutine to fetch the DataMappingInstance + + + :returns: The fetched DataMappingInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DataMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DataMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def patch( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> "DataMappingInstance": + """ + Patch the DataMappingInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param data_mapping_core: + + :returns: The patched DataMappingInstance + """ + return self._proxy.patch( + if_match=if_match, + data_mapping_core=data_mapping_core, + ) + + async def patch_async( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> "DataMappingInstance": + """ + Asynchronous coroutine to patch the DataMappingInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param data_mapping_core: + + :returns: The patched DataMappingInstance + """ + return await self._proxy.patch_async( + if_match=if_match, + data_mapping_core=data_mapping_core, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DataMappingContext(InstanceContext): + + def __init__(self, version: Version, store_id: str, data_mapping_id: str): + """ + Initialize the DataMappingContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param data_mapping_id: A unique DataMapping ID using Twilio Type ID (TTID) format + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "data_mapping_id": data_mapping_id, + } + self._uri = ( + "/ControlPlane/Stores/{store_id}/DataMappings/{data_mapping_id}".format( + **self._solution + ) + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the DataMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DataMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DataMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DataMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DataMappingInstance: + """ + Fetch the DataMappingInstance + + + :returns: The fetched DataMappingInstance + """ + payload, _, _ = self._fetch() + return DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DataMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DataMappingInstance: + """ + Asynchronous coroutine to fetch the DataMappingInstance + + + :returns: The fetched DataMappingInstance + """ + payload, _, _ = await self._fetch_async() + return DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DataMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = data_mapping_core.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["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> DataMappingInstance: + """ + Patch the DataMappingInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param data_mapping_core: + + :returns: The patched DataMappingInstance + """ + payload, _, _ = self._patch( + if_match=if_match, data_mapping_core=data_mapping_core + ) + return DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + + def patch_with_http_info( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> ApiResponse: + """ + Patch the DataMappingInstance and return response metadata + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param data_mapping_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch( + if_match=if_match, data_mapping_core=data_mapping_core + ) + instance = DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = data_mapping_core.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["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> DataMappingInstance: + """ + Asynchronous coroutine to patch the DataMappingInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param data_mapping_core: + + :returns: The patched DataMappingInstance + """ + payload, _, _ = await self._patch_async( + if_match=if_match, data_mapping_core=data_mapping_core + ) + return DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + + async def patch_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the DataMappingInstance and return response metadata + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param data_mapping_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + if_match=if_match, data_mapping_core=data_mapping_core + ) + instance = DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 DataMappingPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> DataMappingInstance: + """ + Build an instance of DataMappingInstance + + :param payload: Payload response from the API + """ + + return DataMappingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DataMappingList(ListResource): + + class CreateDataMappingInput(object): + """ + :ivar display_name: Name of the data mapping. + :ivar description: A human readable description of this resource, up to 512 characters. + :ivar is_enabled: Flag indicating whether the data mapping is active. When true, data will be ingested and mapped according to the configuration. When false, the data mapping will be inactive and no data will be ingested into the Memory Store. + :ivar mapping_to: + :ivar mapping_from: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.is_enabled: Optional[bool] = payload.get("isEnabled") + self.mapping_to: Optional[DataMappingList.DataMappingToTraits] = ( + payload.get("mappingTo") + ) + self.mapping_from: Optional[DataMappingList.DataMappingFromDataSet] = ( + payload.get("mappingFrom") + ) + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "isEnabled": self.is_enabled, + "mappingTo": ( + self.mapping_to.to_dict() if self.mapping_to is not None else None + ), + "mappingFrom": ( + self.mapping_from.to_dict() + if self.mapping_from is not None + else None + ), + } + + class DataMappingCore(object): + """ + :ivar display_name: Name of the data mapping. + :ivar description: A human readable description of this resource, up to 512 characters. + :ivar is_enabled: Flag indicating whether the data mapping is active. When true, data will be ingested and mapped according to the configuration. When false, the data mapping will be inactive and no data will be ingested into the Memory Store. + :ivar mapping_to: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.is_enabled: Optional[bool] = payload.get("isEnabled") + self.mapping_to: Optional[DataMappingList.DataMappingToTraits] = ( + payload.get("mappingTo") + ) + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "isEnabled": self.is_enabled, + "mappingTo": ( + self.mapping_to.to_dict() if self.mapping_to is not None else None + ), + } + + class DataMappingFromDataSet(object): + """ + :ivar type: The source data type, which determines the source of the data and the required configuration parameters. + :ivar dataset_id: The unique identifier of the TDI dataset to connect. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["DataMappingInstance.str"] = payload.get("type") + self.dataset_id: Optional[str] = payload.get("datasetId") + + def to_dict(self): + return { + "type": self.type, + "datasetId": self.dataset_id, + } + + class DataMappingToTraits(object): + """ + :ivar type: The destination data type, which determines where to write the data and the required configuration parameters. + :ivar mappings: The list of field to trait mappings. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["DataMappingInstance.str"] = payload.get("type") + self.mappings: Optional[List[DataMappingList.MappingTraitItem]] = ( + payload.get("mappings") + ) + + def to_dict(self): + return { + "type": self.type, + "mappings": ( + [mappings.to_dict() for mappings in self.mappings] + if self.mappings is not None + else None + ), + } + + class MappingTraitItem(object): + """ + :ivar field_name: The name of the field/column in the source. Deprecated in favor of expression. + :ivar expression: The expression identifying the field/column in the source. + :ivar trait_group: The name of the Trait Group to map to. + :ivar trait_name: The name of the trait within the Trait Group to map to. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.field_name: Optional[str] = payload.get("fieldName") + self.expression: Optional[str] = payload.get("expression") + self.trait_group: Optional[str] = payload.get("traitGroup") + self.trait_name: Optional[str] = payload.get("traitName") + + def to_dict(self): + return { + "fieldName": self.field_name, + "expression": self.expression, + "traitGroup": self.trait_group, + "traitName": self.trait_name, + } + + def __init__(self, version: Version, store_id: str): + """ + Initialize the DataMappingList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/ControlPlane/Stores/{store_id}/DataMappings".format( + **self._solution + ) + + def _create(self, create_data_mapping_input: CreateDataMappingInput) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_data_mapping_input.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_data_mapping_input: CreateDataMappingInput + ) -> DataMappingInstance: + """ + Create the DataMappingInstance + + :param create_data_mapping_input: + + :returns: The created DataMappingInstance + """ + payload, _, _ = self._create( + create_data_mapping_input=create_data_mapping_input + ) + return DataMappingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def create_with_http_info( + self, create_data_mapping_input: CreateDataMappingInput + ) -> ApiResponse: + """ + Create the DataMappingInstance and return response metadata + + :param create_data_mapping_input: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_data_mapping_input=create_data_mapping_input + ) + instance = DataMappingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_data_mapping_input: CreateDataMappingInput + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_data_mapping_input.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_data_mapping_input: CreateDataMappingInput + ) -> DataMappingInstance: + """ + Asynchronously create the DataMappingInstance + + :param create_data_mapping_input: + + :returns: The created DataMappingInstance + """ + payload, _, _ = await self._create_async( + create_data_mapping_input=create_data_mapping_input + ) + return DataMappingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + async def create_with_http_info_async( + self, create_data_mapping_input: CreateDataMappingInput + ) -> ApiResponse: + """ + Asynchronously create the DataMappingInstance and return response metadata + + :param create_data_mapping_input: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_data_mapping_input=create_data_mapping_input + ) + instance = DataMappingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DataMappingInstance]: + """ + Streams DataMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by type. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, + order_by=order_by, + type=type, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DataMappingInstance]: + """ + Asynchronously streams DataMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by type. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, + order_by=order_by, + type=type, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DataMappingInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, + order_by=order_by, + type=type, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DataMappingInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, + order_by=order_by, + type=type, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DataMappingInstance]: + """ + Lists DataMappingInstance 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: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by 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( + page_token=page_token, + order_by=order_by, + type=type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DataMappingInstance]: + """ + Asynchronously lists DataMappingInstance 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: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by 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( + page_token=page_token, + order_by=order_by, + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DataMappingInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + order_by=order_by, + type=type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DataMappingInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + order_by=order_by, + type=type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + ) -> DataMappingPage: + """ + Retrieve a single page of DataMappingInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param type: Filter data mappings by type. + :returns: Page of DataMappingInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + "type": type, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DataMappingPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + ) -> DataMappingPage: + """ + Asynchronously retrieve a single page of DataMappingInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param type: Filter data mappings by type. + :returns: Page of DataMappingInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + "type": type, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DataMappingPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param type: Filter data mappings by 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: ApiResponse with DataMappingPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DataMappingPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param type: Filter data mappings by 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: ApiResponse with DataMappingPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DataMappingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> DataMappingPage: + """ + Retrieve a specific page of DataMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DataMappingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DataMappingPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> DataMappingPage: + """ + Asynchronously retrieve a specific page of DataMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DataMappingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DataMappingPage(self._version, response, solution=self._solution) + + def get(self, data_mapping_id: str) -> DataMappingContext: + """ + Constructs a DataMappingContext + + :param data_mapping_id: A unique DataMapping ID using Twilio Type ID (TTID) format + """ + return DataMappingContext( + self._version, + store_id=self._solution["store_id"], + data_mapping_id=data_mapping_id, + ) + + def __call__(self, data_mapping_id: str) -> DataMappingContext: + """ + Constructs a DataMappingContext + + :param data_mapping_id: A unique DataMapping ID using Twilio Type ID (TTID) format + """ + return DataMappingContext( + self._version, + store_id=self._solution["store_id"], + data_mapping_id=data_mapping_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/event.py b/twilio/rest/memory/v1/event.py new file mode 100644 index 0000000000..39d17cd57d --- /dev/null +++ b/twilio/rest/memory/v1/event.py @@ -0,0 +1,315 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class EventInstance(InstanceResource): + """ + :ivar message: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], store_id: str, profile_id: str + ): + super().__init__(version) + + self.message: Optional[str] = payload.get("message") + + # Only set _solution if path params are provided (not None) + if store_id is not None or profile_id is not None: + self._solution = { + "store_id": store_id, + "profile_id": profile_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 EventList(ListResource): + + class CommunicationLifecycleEventRecipient(object): + """ + :ivar address: The recipient's address. Must be a valid address matching the channel type such as E.164 format for phone numbers. + :ivar participant_id: The unique identifier for the recipient participant. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.address: Optional[str] = payload.get("address") + self.participant_id: Optional[str] = payload.get("participantId") + + def to_dict(self): + return { + "address": self.address, + "participantId": self.participant_id, + } + + class CommunicationLifecycleEventSender(object): + """ + :ivar address: The sender's address. Must be a valid address matching the channel type such as E.164 format for phone numbers. + :ivar participant_id: The unique identifier for the sender participant. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.address: Optional[str] = payload.get("address") + self.participant_id: Optional[str] = payload.get("participantId") + + def to_dict(self): + return { + "address": self.address, + "participantId": self.participant_id, + } + + class ProfileEventRequest(object): + """ + :ivar type: The type of event being sent. + :ivar events: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["EventInstance.str"] = payload.get("type") + self.events: Optional[List[EventList.ProfileEventRequestEvents]] = ( + payload.get("events") + ) + + def to_dict(self): + return { + "type": self.type, + "events": ( + [events.to_dict() for events in self.events] + if self.events is not None + else None + ), + } + + class ProfileEventRequestEvents(object): + """ + :ivar timestamp: The time the event occurred in ISO8601 format with millisecond resolution. Defaults to received time if not provided. + :ivar lifecycle: The lifecycle event type of the communication. + :ivar conversation_id: The unique identifier for the conversation. + :ivar communication_id: The unique identifier for the communication. + :ivar communication_type: The communication channel type. + :ivar communication_status: The lifecycle status of the communication. + :ivar direction: The direction of the communication. + :ivar sender: + :ivar recipient: + :ivar error_code: Error code for FAILED communication status. + :ivar error_message: Error message for FAILED communication status. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.timestamp: Optional[datetime] = payload.get("timestamp") + self.lifecycle: Optional[str] = payload.get("lifecycle") + self.conversation_id: Optional[str] = payload.get("conversationId") + self.communication_id: Optional[str] = payload.get("communicationId") + self.communication_type: Optional[str] = payload.get("communicationType") + self.communication_status: Optional[str] = payload.get( + "communicationStatus" + ) + self.direction: Optional["EventInstance.str"] = payload.get("direction") + self.sender: Optional[EventList.CommunicationLifecycleEventSender] = ( + payload.get("sender") + ) + self.recipient: Optional[EventList.CommunicationLifecycleEventRecipient] = ( + payload.get("recipient") + ) + self.error_code: Optional[str] = payload.get("errorCode") + self.error_message: Optional[str] = payload.get("errorMessage") + + def to_dict(self): + return { + "timestamp": self.timestamp, + "lifecycle": self.lifecycle, + "conversationId": self.conversation_id, + "communicationId": self.communication_id, + "communicationType": self.communication_type, + "communicationStatus": self.communication_status, + "direction": self.direction, + "sender": self.sender.to_dict() if self.sender is not None else None, + "recipient": ( + self.recipient.to_dict() if self.recipient is not None else None + ), + "errorCode": self.error_code, + "errorMessage": self.error_message, + } + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the EventList + + :param version: Version that contains the resource + :param store_id: The storeId identifier + :param profile_id: The profileId identifier + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/Events".format( + **self._solution + ) + + def _create( + self, profile_event_request: Union[ProfileEventRequest, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = profile_event_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, profile_event_request: Union[ProfileEventRequest, object] = values.unset + ) -> EventInstance: + """ + Create the EventInstance + + :param profile_event_request: + + :returns: The created EventInstance + """ + payload, _, _ = self._create(profile_event_request=profile_event_request) + return EventInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def create_with_http_info( + self, profile_event_request: Union[ProfileEventRequest, object] = values.unset + ) -> ApiResponse: + """ + Create the EventInstance and return response metadata + + :param profile_event_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + profile_event_request=profile_event_request + ) + instance = EventInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, profile_event_request: Union[ProfileEventRequest, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = profile_event_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, profile_event_request: Union[ProfileEventRequest, object] = values.unset + ) -> EventInstance: + """ + Asynchronously create the EventInstance + + :param profile_event_request: + + :returns: The created EventInstance + """ + payload, _, _ = await self._create_async( + profile_event_request=profile_event_request + ) + return EventInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + async def create_with_http_info_async( + self, profile_event_request: Union[ProfileEventRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the EventInstance and return response metadata + + :param profile_event_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + profile_event_request=profile_event_request + ) + instance = EventInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/identifier.py b/twilio/rest/memory/v1/identifier.py new file mode 100644 index 0000000000..3ac08f718b --- /dev/null +++ b/twilio/rest/memory/v1/identifier.py @@ -0,0 +1,1010 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Union +from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class IdentifierInstance(InstanceResource): + """ + :ivar message: + :ivar id_type: Identifier type defined in Identity Resolution Settings. + :ivar values: Server managed collection of stored values for the identifier type. Identifier values are normalized according to the corresponding identifier settings and ordered chronologically. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: str, + profile_id: str, + id_type: Optional[str] = None, + ): + super().__init__(version) + + self.message: Optional[str] = payload.get("message") + self.id_type: Optional[str] = payload.get("idType") + self.values: Optional[List[str]] = payload.get("values") + + # Only set _solution if path params are provided (not None) + if store_id is not None or profile_id is not None or id_type is not None: + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "id_type": id_type, + } + + self._context: Optional[IdentifierContext] = None + + @property + def _proxy(self) -> "IdentifierContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IdentifierContext for this IdentifierInstance + """ + if self._context is None: + self._context = IdentifierContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + return self._context + + def delete(self, remove_all: Union[bool, object] = values.unset) -> bool: + """ + Deletes the IdentifierInstance + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + remove_all=remove_all, + ) + + async def delete_async( + self, remove_all: Union[bool, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the IdentifierInstance + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + remove_all=remove_all, + ) + + def delete_with_http_info( + self, remove_all: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Deletes the IdentifierInstance with HTTP info + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + remove_all=remove_all, + ) + + async def delete_with_http_info_async( + self, remove_all: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IdentifierInstance with HTTP info + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + remove_all=remove_all, + ) + + def fetch(self) -> "IdentifierInstance": + """ + Fetch the IdentifierInstance + + + :returns: The fetched IdentifierInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IdentifierInstance": + """ + Asynchronous coroutine to fetch the IdentifierInstance + + + :returns: The fetched IdentifierInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IdentifierInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IdentifierInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def patch(self, identifier_update: IdentifierUpdate) -> "IdentifierInstance": + """ + Patch the IdentifierInstance + + :param identifier_update: + + :returns: The patched IdentifierInstance + """ + return self._proxy.patch( + identifier_update=identifier_update, + ) + + async def patch_async( + self, identifier_update: IdentifierUpdate + ) -> "IdentifierInstance": + """ + Asynchronous coroutine to patch the IdentifierInstance + + :param identifier_update: + + :returns: The patched IdentifierInstance + """ + return await self._proxy.patch_async( + identifier_update=identifier_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 IdentifierContext(InstanceContext): + + def __init__(self, version: Version, store_id: str, profile_id: str, id_type: str): + """ + Initialize the IdentifierContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + :param id_type: Identifier type configured for the service (for example `email`, `phone`, or `externalId`). + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "id_type": id_type, + } + self._uri = ( + "/Stores/{store_id}/Profiles/{profile_id}/Identifiers/{id_type}".format( + **self._solution + ) + ) + + def _delete(self, remove_all: Union[bool, object] = values.unset) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "removeAll": serialize.boolean_to_string(remove_all), + } + ) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers, params=params + ) + + def delete(self, remove_all: Union[bool, object] = values.unset) -> bool: + """ + Deletes the IdentifierInstance + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete(remove_all=remove_all) + return success + + def delete_with_http_info( + self, remove_all: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Deletes the IdentifierInstance and return response metadata + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(remove_all=remove_all) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, remove_all: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "removeAll": serialize.boolean_to_string(remove_all), + } + ) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers, params=params + ) + + async def delete_async( + self, remove_all: Union[bool, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the IdentifierInstance + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async(remove_all=remove_all) + return success + + async def delete_with_http_info_async( + self, remove_all: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IdentifierInstance and return response metadata + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async(remove_all=remove_all) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> IdentifierInstance: + """ + Fetch the IdentifierInstance + + + :returns: The fetched IdentifierInstance + """ + payload, _, _ = self._fetch() + return IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IdentifierInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> IdentifierInstance: + """ + Asynchronous coroutine to fetch the IdentifierInstance + + + :returns: The fetched IdentifierInstance + """ + payload, _, _ = await self._fetch_async() + return IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IdentifierInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch(self, identifier_update: IdentifierUpdate) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identifier_update.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch(self, identifier_update: IdentifierUpdate) -> IdentifierInstance: + """ + Patch the IdentifierInstance + + :param identifier_update: + + :returns: The patched IdentifierInstance + """ + payload, _, _ = self._patch(identifier_update=identifier_update) + return IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + + def patch_with_http_info(self, identifier_update: IdentifierUpdate) -> ApiResponse: + """ + Patch the IdentifierInstance and return response metadata + + :param identifier_update: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch(identifier_update=identifier_update) + instance = IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async(self, identifier_update: IdentifierUpdate) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identifier_update.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async( + self, identifier_update: IdentifierUpdate + ) -> IdentifierInstance: + """ + Asynchronous coroutine to patch the IdentifierInstance + + :param identifier_update: + + :returns: The patched IdentifierInstance + """ + payload, _, _ = await self._patch_async(identifier_update=identifier_update) + return IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + + async def patch_with_http_info_async( + self, identifier_update: IdentifierUpdate + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the IdentifierInstance and return response metadata + + :param identifier_update: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + identifier_update=identifier_update + ) + instance = IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 IdentifierPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> IdentifierInstance: + """ + Build an instance of IdentifierInstance + + :param payload: Payload response from the API + """ + + return IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class IdentifierList(ListResource): + + class Identifier(object): + """ + :ivar id_type: Identifier type as configured in the service's Identity Resolution Settings. + :ivar value: Raw value captured for the identifier. The service may normalize this value according to the `normalization` rule defined in the identifier settings before storage or matching (for example E.164 formatting for phone numbers). + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id_type: Optional[str] = payload.get("idType") + self.value: Optional[str] = payload.get("value") + + def to_dict(self): + return { + "idType": self.id_type, + "value": self.value, + } + + class IdentifierUpdate(object): + """ + :ivar id_type: The identifier type to update (e.g., email, phone). + :ivar old_value: Existing stored value to replace. + :ivar new_value: New value to store for the identifier. Normalization rules from the corresponding identifier settings apply. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id_type: Optional[str] = payload.get("idType") + self.old_value: Optional[str] = payload.get("oldValue") + self.new_value: Optional[str] = payload.get("newValue") + + def to_dict(self): + return { + "idType": self.id_type, + "oldValue": self.old_value, + "newValue": self.new_value, + } + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the IdentifierList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/Identifiers".format( + **self._solution + ) + + def _create(self, identifier: Identifier) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identifier.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, identifier: Identifier) -> IdentifierInstance: + """ + Create the IdentifierInstance + + :param identifier: + + :returns: The created IdentifierInstance + """ + payload, _, _ = self._create(identifier=identifier) + return IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def create_with_http_info(self, identifier: Identifier) -> ApiResponse: + """ + Create the IdentifierInstance and return response metadata + + :param identifier: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(identifier=identifier) + instance = IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, identifier: Identifier) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identifier.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, identifier: Identifier) -> IdentifierInstance: + """ + Asynchronously create the IdentifierInstance + + :param identifier: + + :returns: The created IdentifierInstance + """ + payload, _, _ = await self._create_async(identifier=identifier) + return IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + async def create_with_http_info_async(self, identifier: Identifier) -> ApiResponse: + """ + Asynchronously create the IdentifierInstance and return response metadata + + :param identifier: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(identifier=identifier) + instance = IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def list( + self, + ) -> List[IdentifierInstance]: + """ + Lists IdentifierInstance records from the API as a list. + + :returns: list that will contain up to limit results + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + data = values.of({}) + payload, _, _ = self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return [ + IdentifierInstance( + self._version, + item, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + for item in payload["identifiers"] + ] + + async def list_async( + self, + ) -> List[IdentifierInstance]: + """ + Asynchronously lists IdentifierInstance records from the API as a list. + + :returns: list that will contain up to limit results + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + data = values.of({}) + payload, _, _ = await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return [ + IdentifierInstance( + self._version, + item, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + for item in payload["identifiers"] + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists IdentifierInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists IdentifierInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + ) -> IdentifierPage: + """ + Retrieve a single page of IdentifierInstance records from the API. + Request is executed immediately + + :returns: Page of IdentifierInstance + """ + data = values.of({}) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IdentifierPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + ) -> IdentifierPage: + """ + Asynchronously retrieve a single page of IdentifierInstance records from the API. + Request is executed immediately + + :returns: Page of IdentifierInstance + """ + data = values.of({}) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IdentifierPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IdentifierPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IdentifierPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IdentifierPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IdentifierPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> IdentifierPage: + """ + Retrieve a specific page of IdentifierInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IdentifierInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IdentifierPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> IdentifierPage: + """ + Asynchronously retrieve a specific page of IdentifierInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IdentifierInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IdentifierPage(self._version, response, solution=self._solution) + + def get(self, id_type: str) -> IdentifierContext: + """ + Constructs a IdentifierContext + + :param id_type: Identifier type configured for the service (for example `email`, `phone`, or `externalId`). + """ + return IdentifierContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=id_type, + ) + + def __call__(self, id_type: str) -> IdentifierContext: + """ + Constructs a IdentifierContext + + :param id_type: Identifier type configured for the service (for example `email`, `phone`, or `externalId`). + """ + return IdentifierContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=id_type, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/identity_resolution_setting.py b/twilio/rest/memory/v1/identity_resolution_setting.py new file mode 100644 index 0000000000..c575c283b0 --- /dev/null +++ b/twilio/rest/memory/v1/identity_resolution_setting.py @@ -0,0 +1,548 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.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 IdentityResolutionSettingInstance(InstanceResource): + """ + :ivar identifier_configs: List of identifier types and their resolution settings. + :ivar matching_rules: Priority list of identifiers to locate profiles to apply new data to, or for determining if two existing profiles should merge. Rules are evaluated in order. - If no rule matches against existing profiles, a new profile will be created. - If a rule matches to a single existing profile, the profile will be updated. - If a rule matches to multiple existing profiles, those existing profiles will be merged. + :ivar version: The current version number of the Identity Resolution Settings. Incremented on each successful update. + :ivar message: + :ivar status_url: URI to check operation status. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: Optional[str] = None, + ): + super().__init__(version) + + self.identifier_configs: Optional[List[str]] = payload.get("identifierConfigs") + self.matching_rules: Optional[List[str]] = payload.get("matchingRules") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.message: Optional[str] = payload.get("message") + self.status_url: Optional[str] = payload.get("statusUrl") + + # Only set _solution if path params are provided (not None) + if store_id is not None: + self._solution = { + "store_id": store_id, + } + + self._context: Optional[IdentityResolutionSettingContext] = None + + @property + def _proxy(self) -> "IdentityResolutionSettingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IdentityResolutionSettingContext for this IdentityResolutionSettingInstance + """ + if self._context is None: + self._context = IdentityResolutionSettingContext( + self._version, + store_id=self._solution["store_id"], + ) + return self._context + + def fetch(self) -> "IdentityResolutionSettingInstance": + """ + Fetch the IdentityResolutionSettingInstance + + + :returns: The fetched IdentityResolutionSettingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IdentityResolutionSettingInstance": + """ + Asynchronous coroutine to fetch the IdentityResolutionSettingInstance + + + :returns: The fetched IdentityResolutionSettingInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IdentityResolutionSettingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IdentityResolutionSettingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> "IdentityResolutionSettingInstance": + """ + Update the IdentityResolutionSettingInstance + + :param identity_resolution_settings_core: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: The updated IdentityResolutionSettingInstance + """ + return self._proxy.update( + identity_resolution_settings_core=identity_resolution_settings_core, + if_match=if_match, + ) + + async def update_async( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> "IdentityResolutionSettingInstance": + """ + Asynchronous coroutine to update the IdentityResolutionSettingInstance + + :param identity_resolution_settings_core: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: The updated IdentityResolutionSettingInstance + """ + return await self._proxy.update_async( + identity_resolution_settings_core=identity_resolution_settings_core, + if_match=if_match, + ) + + def update_with_http_info( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the IdentityResolutionSettingInstance with HTTP info + + :param identity_resolution_settings_core: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + identity_resolution_settings_core=identity_resolution_settings_core, + if_match=if_match, + ) + + async def update_with_http_info_async( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IdentityResolutionSettingInstance with HTTP info + + :param identity_resolution_settings_core: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + identity_resolution_settings_core=identity_resolution_settings_core, + 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 IdentityResolutionSettingContext(InstanceContext): + + def __init__(self, version: Version, store_id: str): + """ + Initialize the IdentityResolutionSettingContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/ControlPlane/Stores/{store_id}/IdentityResolutionSettings".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> IdentityResolutionSettingInstance: + """ + Fetch the IdentityResolutionSettingInstance + + + :returns: The fetched IdentityResolutionSettingInstance + """ + payload, _, _ = self._fetch() + return IdentityResolutionSettingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IdentityResolutionSettingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = IdentityResolutionSettingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> IdentityResolutionSettingInstance: + """ + Asynchronous coroutine to fetch the IdentityResolutionSettingInstance + + + :returns: The fetched IdentityResolutionSettingInstance + """ + payload, _, _ = await self._fetch_async() + return IdentityResolutionSettingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IdentityResolutionSettingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = IdentityResolutionSettingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identity_resolution_settings_core.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["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> IdentityResolutionSettingInstance: + """ + Update the IdentityResolutionSettingInstance + + :param identity_resolution_settings_core: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: The updated IdentityResolutionSettingInstance + """ + payload, _, _ = self._update( + identity_resolution_settings_core=identity_resolution_settings_core, + if_match=if_match, + ) + return IdentityResolutionSettingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def update_with_http_info( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the IdentityResolutionSettingInstance and return response metadata + + :param identity_resolution_settings_core: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + identity_resolution_settings_core=identity_resolution_settings_core, + if_match=if_match, + ) + instance = IdentityResolutionSettingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identity_resolution_settings_core.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["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> IdentityResolutionSettingInstance: + """ + Asynchronous coroutine to update the IdentityResolutionSettingInstance + + :param identity_resolution_settings_core: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: The updated IdentityResolutionSettingInstance + """ + payload, _, _ = await self._update_async( + identity_resolution_settings_core=identity_resolution_settings_core, + if_match=if_match, + ) + return IdentityResolutionSettingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + async def update_with_http_info_async( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IdentityResolutionSettingInstance and return response metadata + + :param identity_resolution_settings_core: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + identity_resolution_settings_core=identity_resolution_settings_core, + if_match=if_match, + ) + instance = IdentityResolutionSettingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 IdentityResolutionSettingList(ListResource): + + class IdentifierConfig(object): + """ + :ivar id_type: Name of the identifier type. Usual values are email, phone, external_id etc. + :ivar matching_algo: The algorithm to use for matching identifier values. - `exact`, exact string match. - `fuzzy`, low precision match allowing for some variations. + :ivar matching_threshold: The `fuzzy` matching threshold percentage. + :ivar limit: Maximum number of historical values to retain. + :ivar limit_policy: Removal policy to apply when the number of values exceeds the limit and is based on the timestamp of the request when the identifier was added. - `fifo`: First In First Out, removes the oldest values first. - `lifo`: Last In First Out, removes the most recent values first. + :ivar enforce_unique: When enabled, more than one profile may not share the same identifier value. Adding a shared identifier to a second profile may trigger a merge. Disabling creates a compound identifier where merges are only triggered if two or more identifiers satisfy a matching rule. + :ivar normalization: Normalization to apply to the identifier value before storing and matching. - `phone`: Normalize phone numbers to E.164 format. - `email`: Normalize email addresses by coverting to lowercase and removing spaces. - `trim`: Removes spaces from both ends of the string. - `none`: No normalization. **Important Note for Phone Number Normalization:** When using the `phone` normalization option, please adhere to the following guidelines to ensure proper formatting: - All US numbers must be at least valid 10 digit phone numbers with area code. They may also include or omit the \"+1\" prefix. - Non-US numbers must include a 1-3 digit country code (a \"+\" prefix is optional). Non-US national formats are not supported and will be interpreted as US numbers. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id_type: Optional[str] = payload.get("idType") + self.matching_algo: Optional["IdentityResolutionSettingInstance.str"] = ( + payload.get("matchingAlgo") + ) + self.matching_threshold: Optional[int] = payload.get("matchingThreshold") + self.limit: Optional[int] = payload.get("limit") + self.limit_policy: Optional["IdentityResolutionSettingInstance.str"] = ( + payload.get("limitPolicy") + ) + self.enforce_unique: Optional[bool] = payload.get("enforceUnique") + self.normalization: Optional["IdentityResolutionSettingInstance.str"] = ( + payload.get("normalization") + ) + + def to_dict(self): + return { + "idType": self.id_type, + "matchingAlgo": self.matching_algo, + "matchingThreshold": self.matching_threshold, + "limit": self.limit, + "limitPolicy": self.limit_policy, + "enforceUnique": self.enforce_unique, + "normalization": self.normalization, + } + + class IdentityResolutionSettingsCore(object): + """ + :ivar identifier_configs: List of identifier types and their resolution settings. + :ivar matching_rules: Priority list of identifiers to locate profiles to apply new data to, or for determining if two existing profiles should merge. Rules are evaluated in order. - If no rule matches against existing profiles, a new profile will be created. - If a rule matches to a single existing profile, the profile will be updated. - If a rule matches to multiple existing profiles, those existing profiles will be merged. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.identifier_configs: Optional[ + List[IdentityResolutionSettingList.IdentifierConfig] + ] = payload.get("identifierConfigs") + self.matching_rules: Optional[List[str]] = payload.get("matchingRules") + + def to_dict(self): + return { + "identifierConfigs": ( + [ + identifier_configs.to_dict() + for identifier_configs in self.identifier_configs + ] + if self.identifier_configs is not None + else None + ), + "matchingRules": self.matching_rules, + } + + def __init__(self, version: Version): + """ + Initialize the IdentityResolutionSettingList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, store_id: str) -> IdentityResolutionSettingContext: + """ + Constructs a IdentityResolutionSettingContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return IdentityResolutionSettingContext(self._version, store_id=store_id) + + def __call__(self, store_id: str) -> IdentityResolutionSettingContext: + """ + Constructs a IdentityResolutionSettingContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return IdentityResolutionSettingContext(self._version, store_id=store_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/import_.py b/twilio/rest/memory/v1/import_.py new file mode 100644 index 0000000000..73a65e96e1 --- /dev/null +++ b/twilio/rest/memory/v1/import_.py @@ -0,0 +1,738 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ImportInstance(InstanceResource): + """ + :ivar imports: + :ivar status: Current processing status of the import task + :ivar filename: Original filename of the uploaded CSV + :ivar created_at: Timestamp when the import was created + :ivar updated_at: Timestamp when the import was last updated + :ivar file_size: Size of the uploaded file in bytes (1 byte to 100 MiB) + :ivar column_mappings: Mappings of CSV header columns to traits' fields + :ivar summary: + :ivar import_id: ID of the import task. + :ivar url: Pre-signed URL to upload the CSV via a single PUT request. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: str, + import_id: Optional[str] = None, + ): + super().__init__(version) + + self.imports: Optional[List[str]] = payload.get("imports") + self.status: Optional["ImportInstance.str"] = payload.get("status") + self.filename: Optional[str] = payload.get("filename") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.file_size: Optional[int] = deserialize.integer(payload.get("fileSize")) + self.column_mappings: Optional[List[ColumnMappingItem]] = payload.get( + "columnMappings" + ) + self.summary: Optional[FetchProfileImportV2200ResponseSummary] = payload.get( + "summary" + ) + self.import_id: Optional[str] = payload.get("importId") + self.url: Optional[str] = payload.get("url") + + # Only set _solution if path params are provided (not None) + if store_id is not None or import_id is not None: + self._solution = { + "store_id": store_id, + "import_id": import_id, + } + + self._context: Optional[ImportContext] = None + + @property + def _proxy(self) -> "ImportContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ImportContext for this ImportInstance + """ + if self._context is None: + self._context = ImportContext( + self._version, + store_id=self._solution["store_id"], + import_id=self._solution["import_id"], + ) + return self._context + + def fetch(self) -> "ImportInstance": + """ + Fetch the ImportInstance + + + :returns: The fetched ImportInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ImportInstance": + """ + Asynchronous coroutine to fetch the ImportInstance + + + :returns: The fetched ImportInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ImportInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ImportInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 ImportContext(InstanceContext): + + def __init__(self, version: Version, store_id: str, import_id: str): + """ + Initialize the ImportContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param import_id: The task identifier for the import process. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "import_id": import_id, + } + self._uri = "/Stores/{store_id}/Profiles/Imports/{import_id}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ImportInstance: + """ + Fetch the ImportInstance + + + :returns: The fetched ImportInstance + """ + payload, _, _ = self._fetch() + return ImportInstance( + self._version, + payload, + store_id=self._solution["store_id"], + import_id=self._solution["import_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ImportInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ImportInstance( + self._version, + payload, + store_id=self._solution["store_id"], + import_id=self._solution["import_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ImportInstance: + """ + Asynchronous coroutine to fetch the ImportInstance + + + :returns: The fetched ImportInstance + """ + payload, _, _ = await self._fetch_async() + return ImportInstance( + self._version, + payload, + store_id=self._solution["store_id"], + import_id=self._solution["import_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ImportInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ImportInstance( + self._version, + payload, + store_id=self._solution["store_id"], + import_id=self._solution["import_id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 ImportPage(TokenPagination): + + def get_instance(self, payload: str) -> str: + """ + Build an instance of str + + :param payload: Payload response from the API + """ + + return payload # Return string ID directly + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ImportList(ListResource): + + class ColumnMappingItem(object): + """ + :ivar column_name: The name of the column in the CSV header + :ivar trait_group: The trait group to which this trait belongs + :ivar trait_name: The name of the trait in the trait group + """ + + def __init__(self, payload: Dict[str, Any]): + + self.column_name: Optional[str] = payload.get("columnName") + self.trait_group: Optional[str] = payload.get("traitGroup") + self.trait_name: Optional[str] = payload.get("traitName") + + def to_dict(self): + return { + "columnName": self.column_name, + "traitGroup": self.trait_group, + "traitName": self.trait_name, + } + + class CreateProfilesImportV2Request(object): + """ + :ivar filename: The name of the file to generate a presigned URL + :ivar file_size: The size of the file in bytes (1 byte to 100 MiB) + :ivar column_mappings: Mappings of CSV header columns to traits' fields + """ + + def __init__(self, payload: Dict[str, Any]): + + self.filename: Optional[str] = payload.get("filename") + self.file_size: Optional[int] = payload.get("fileSize") + self.column_mappings: Optional[List[ImportList.ColumnMappingItem]] = ( + payload.get("columnMappings") + ) + + def to_dict(self): + return { + "filename": self.filename, + "fileSize": self.file_size, + "columnMappings": ( + [ + column_mappings.to_dict() + for column_mappings in self.column_mappings + ] + if self.column_mappings is not None + else None + ), + } + + class FetchProfileImportV2200ResponseSummary(object): + """ + :ivar errors: Total count of errors encountered during import + :ivar warnings: Total count of warnings encountered during import + """ + + def __init__(self, payload: Dict[str, Any]): + + self.errors: Optional[int] = payload.get("errors") + self.warnings: Optional[int] = payload.get("warnings") + + def to_dict(self): + return { + "errors": self.errors, + "warnings": self.warnings, + } + + def __init__(self, version: Version, store_id: str): + """ + Initialize the ImportList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/Stores/{store_id}/Profiles/Imports".format(**self._solution) + + def _create( + self, create_profiles_import_v2_request: CreateProfilesImportV2Request + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_profiles_import_v2_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_profiles_import_v2_request: CreateProfilesImportV2Request + ) -> ImportInstance: + """ + Create the ImportInstance + + :param create_profiles_import_v2_request: + + :returns: The created ImportInstance + """ + payload, _, _ = self._create( + create_profiles_import_v2_request=create_profiles_import_v2_request + ) + return ImportInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def create_with_http_info( + self, create_profiles_import_v2_request: CreateProfilesImportV2Request + ) -> ApiResponse: + """ + Create the ImportInstance and return response metadata + + :param create_profiles_import_v2_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_profiles_import_v2_request=create_profiles_import_v2_request + ) + instance = ImportInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_profiles_import_v2_request: CreateProfilesImportV2Request + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_profiles_import_v2_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_profiles_import_v2_request: CreateProfilesImportV2Request + ) -> ImportInstance: + """ + Asynchronously create the ImportInstance + + :param create_profiles_import_v2_request: + + :returns: The created ImportInstance + """ + payload, _, _ = await self._create_async( + create_profiles_import_v2_request=create_profiles_import_v2_request + ) + return ImportInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + async def create_with_http_info_async( + self, create_profiles_import_v2_request: CreateProfilesImportV2Request + ) -> ApiResponse: + """ + Asynchronously create the ImportInstance and return response metadata + + :param create_profiles_import_v2_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_profiles_import_v2_request=create_profiles_import_v2_request + ) + instance = ImportInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def list( + self, + ) -> List[str]: + """ + Lists ImportInstance IDs from the API as a list. + + :returns: list that will contain up to limit results + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + data = values.of({}) + payload, _, _ = self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return list(payload["imports"]) + + async def list_async( + self, + ) -> List[str]: + """ + Asynchronously lists ImportInstance IDs from the API as a list. + + :returns: list that will contain up to limit results + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + data = values.of({}) + payload, _, _ = await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return list(payload["imports"]) + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ImportInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ImportInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + ) -> ImportPage: + """ + Retrieve a single page of ImportInstance records from the API. + Request is executed immediately + + :returns: Page of ImportInstance + """ + data = values.of({}) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ImportPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + ) -> ImportPage: + """ + Asynchronously retrieve a single page of ImportInstance records from the API. + Request is executed immediately + + :returns: Page of ImportInstance + """ + data = values.of({}) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ImportPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ImportPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ImportPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ImportPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ImportPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ImportPage: + """ + Retrieve a specific page of ImportInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ImportInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ImportPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ImportPage: + """ + Asynchronously retrieve a specific page of ImportInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ImportInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ImportPage(self._version, response, solution=self._solution) + + def get(self, import_id: str) -> ImportContext: + """ + Constructs a ImportContext + + :param import_id: The task identifier for the import process. + """ + return ImportContext( + self._version, store_id=self._solution["store_id"], import_id=import_id + ) + + def __call__(self, import_id: str) -> ImportContext: + """ + Constructs a ImportContext + + :param import_id: The task identifier for the import process. + """ + return ImportContext( + self._version, store_id=self._solution["store_id"], import_id=import_id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/lookup.py b/twilio/rest/memory/v1/lookup.py new file mode 100644 index 0000000000..11721acfab --- /dev/null +++ b/twilio/rest/memory/v1/lookup.py @@ -0,0 +1,187 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class LookupInstance(InstanceResource): + """ + :ivar normalized_value: Identifier value after normalization that was used for the lookup. + :ivar profiles: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], store_id: str): + super().__init__(version) + + self.normalized_value: Optional[str] = payload.get("normalizedValue") + self.profiles: Optional[List[str]] = payload.get("profiles") + + # Only set _solution if path params are provided (not None) + if store_id is not None: + self._solution = { + "store_id": store_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 LookupList(ListResource): + + class Identifier(object): + """ + :ivar id_type: Identifier type as configured in the service's Identity Resolution Settings. + :ivar value: Raw value captured for the identifier. The service may normalize this value according to the `normalization` rule defined in the identifier settings before storage or matching (for example E.164 formatting for phone numbers). + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id_type: Optional[str] = payload.get("idType") + self.value: Optional[str] = payload.get("value") + + def to_dict(self): + return { + "idType": self.id_type, + "value": self.value, + } + + def __init__(self, version: Version, store_id: str): + """ + Initialize the LookupList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/Stores/{store_id}/Profiles/Lookup".format(**self._solution) + + def _create(self, identifier: Identifier) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identifier.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, identifier: Identifier) -> LookupInstance: + """ + Create the LookupInstance + + :param identifier: + + :returns: The created LookupInstance + """ + payload, _, _ = self._create(identifier=identifier) + return LookupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def create_with_http_info(self, identifier: Identifier) -> ApiResponse: + """ + Create the LookupInstance and return response metadata + + :param identifier: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(identifier=identifier) + instance = LookupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, identifier: Identifier) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identifier.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, identifier: Identifier) -> LookupInstance: + """ + Asynchronously create the LookupInstance + + :param identifier: + + :returns: The created LookupInstance + """ + payload, _, _ = await self._create_async(identifier=identifier) + return LookupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + async def create_with_http_info_async(self, identifier: Identifier) -> ApiResponse: + """ + Asynchronously create the LookupInstance and return response metadata + + :param identifier: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(identifier=identifier) + instance = LookupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/observation.py b/twilio/rest/memory/v1/observation.py new file mode 100644 index 0000000000..9150a75ef0 --- /dev/null +++ b/twilio/rest/memory/v1/observation.py @@ -0,0 +1,1408 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ObservationInstance(InstanceResource): + """ + :ivar content: The main content of the observation. + :ivar occurred_at: The timestamp when the observation originally occurred. + :ivar source: The source system that generated this observation. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :ivar conversation_ids: Array of conversation IDs associated with this observation. + :ivar id: A unique identifier for the observation using Twilio Type ID (TTID) format. + :ivar created_at: The timestamp when the observation was created. + :ivar updated_at: The timestamp when the observation was last updated. + :ivar message: + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: str, + profile_id: str, + observation_id: Optional[str] = None, + ): + super().__init__(version) + + self.content: Optional[str] = payload.get("content") + self.occurred_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("occurredAt") + ) + self.source: Optional[str] = payload.get("source") + self.conversation_ids: Optional[List[str]] = payload.get("conversationIds") + self.id: Optional[str] = payload.get("id") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.message: Optional[str] = payload.get("message") + + # Only set _solution if path params are provided (not None) + if store_id is not None or profile_id is not None or observation_id is not None: + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "observation_id": observation_id, + } + + self._context: Optional[ObservationContext] = None + + @property + def _proxy(self) -> "ObservationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ObservationContext for this ObservationInstance + """ + if self._context is None: + self._context = ObservationContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ObservationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ObservationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ObservationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ObservationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "ObservationInstance": + """ + Fetch the ObservationInstance + + + :returns: The fetched ObservationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ObservationInstance": + """ + Asynchronous coroutine to fetch the ObservationInstance + + + :returns: The fetched ObservationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ObservationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ObservationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def patch(self, observation_core: ObservationCore) -> "ObservationInstance": + """ + Patch the ObservationInstance + + :param observation_core: + + :returns: The patched ObservationInstance + """ + return self._proxy.patch( + observation_core=observation_core, + ) + + async def patch_async( + self, observation_core: ObservationCore + ) -> "ObservationInstance": + """ + Asynchronous coroutine to patch the ObservationInstance + + :param observation_core: + + :returns: The patched ObservationInstance + """ + return await self._proxy.patch_async( + observation_core=observation_core, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ObservationContext(InstanceContext): + + def __init__( + self, version: Version, store_id: str, profile_id: str, observation_id: str + ): + """ + Initialize the ObservationContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + :param observation_id: The observation ID. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "observation_id": observation_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/Observations/{observation_id}".format( + **self._solution + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ObservationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ObservationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ObservationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ObservationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ObservationInstance: + """ + Fetch the ObservationInstance + + + :returns: The fetched ObservationInstance + """ + payload, _, _ = self._fetch() + return ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ObservationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ObservationInstance: + """ + Asynchronous coroutine to fetch the ObservationInstance + + + :returns: The fetched ObservationInstance + """ + payload, _, _ = await self._fetch_async() + return ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ObservationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch(self, observation_core: ObservationCore) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = observation_core.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch(self, observation_core: ObservationCore) -> ObservationInstance: + """ + Patch the ObservationInstance + + :param observation_core: + + :returns: The patched ObservationInstance + """ + payload, _, _ = self._patch(observation_core=observation_core) + return ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + + def patch_with_http_info(self, observation_core: ObservationCore) -> ApiResponse: + """ + Patch the ObservationInstance and return response metadata + + :param observation_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch(observation_core=observation_core) + instance = ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async(self, observation_core: ObservationCore) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = observation_core.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async( + self, observation_core: ObservationCore + ) -> ObservationInstance: + """ + Asynchronous coroutine to patch the ObservationInstance + + :param observation_core: + + :returns: The patched ObservationInstance + """ + payload, _, _ = await self._patch_async(observation_core=observation_core) + return ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + + async def patch_with_http_info_async( + self, observation_core: ObservationCore + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the ObservationInstance and return response metadata + + :param observation_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + observation_core=observation_core + ) + instance = ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 ObservationPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ObservationInstance: + """ + Build an instance of ObservationInstance + + :param payload: Payload response from the API + """ + + return ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ObservationList(ListResource): + + class CreateObservationsRequest(object): + """ + :ivar observations: Array of observations to create in a single batch operation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.observations: Optional[List[ObservationList.ObservationCore]] = ( + payload.get("observations") + ) + + def to_dict(self): + return { + "observations": ( + [observations.to_dict() for observations in self.observations] + if self.observations is not None + else None + ), + } + + class ObservationCore(object): + """ + :ivar content: The main content of the observation. + :ivar occurred_at: The timestamp when the observation originally occurred. + :ivar source: The source system that generated this observation. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :ivar conversation_ids: Array of conversation IDs associated with this observation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.content: Optional[str] = payload.get("content") + self.occurred_at: Optional[datetime] = payload.get("occurredAt") + self.source: Optional[str] = payload.get("source") + self.conversation_ids: Optional[List[str]] = payload.get("conversationIds") + + def to_dict(self): + return { + "content": self.content, + "occurredAt": self.occurred_at, + "source": self.source, + "conversationIds": self.conversation_ids, + } + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the ObservationList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/Observations".format( + **self._solution + ) + + def _create( + self, + create_observations_request: CreateObservationsRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_observations_request.to_dict() + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Encoding": content_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + create_observations_request: CreateObservationsRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ObservationInstance: + """ + Create the ObservationInstance + + :param create_observations_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: The created ObservationInstance + """ + payload, _, _ = self._create( + create_observations_request=create_observations_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + return ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def create_with_http_info( + self, + create_observations_request: CreateObservationsRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ObservationInstance and return response metadata + + :param create_observations_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_observations_request=create_observations_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + instance = ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + create_observations_request: CreateObservationsRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_observations_request.to_dict() + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Encoding": content_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + create_observations_request: CreateObservationsRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ObservationInstance: + """ + Asynchronously create the ObservationInstance + + :param create_observations_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: The created ObservationInstance + """ + payload, _, _ = await self._create_async( + create_observations_request=create_observations_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + return ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + async def create_with_http_info_async( + self, + create_observations_request: CreateObservationsRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ObservationInstance and return response metadata + + :param create_observations_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_observations_request=create_observations_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + instance = ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ObservationInstance]: + """ + Streams ObservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ObservationInstance]: + """ + Asynchronously streams ObservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ObservationInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ObservationInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ObservationInstance]: + """ + Lists ObservationInstance 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: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ObservationInstance]: + """ + Asynchronously lists ObservationInstance 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: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ObservationInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ObservationInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + ) -> ObservationPage: + """ + Retrieve a single page of ObservationInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param created_after: Filter observations created after this timestamp (inclusive). + :param created_before: Filter observations created before this timestamp (exclusive). + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :returns: Page of ObservationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + "source": source, + "createdAfter": serialize.iso8601_datetime(created_after), + "createdBefore": serialize.iso8601_datetime(created_before), + "Accept-Encoding": accept_encoding, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ObservationPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + ) -> ObservationPage: + """ + Asynchronously retrieve a single page of ObservationInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param created_after: Filter observations created after this timestamp (inclusive). + :param created_before: Filter observations created before this timestamp (exclusive). + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :returns: Page of ObservationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + "source": source, + "createdAfter": serialize.iso8601_datetime(created_after), + "createdBefore": serialize.iso8601_datetime(created_before), + "Accept-Encoding": accept_encoding, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ObservationPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param created_after: Filter observations created after this timestamp (inclusive). + :param created_before: Filter observations created before this timestamp (exclusive). + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ObservationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "source": source, + "createdAfter": serialize.iso8601_datetime(created_after), + "createdBefore": serialize.iso8601_datetime(created_before), + "Accept-Encoding": accept_encoding, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ObservationPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param created_after: Filter observations created after this timestamp (inclusive). + :param created_before: Filter observations created before this timestamp (exclusive). + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ObservationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "source": source, + "createdAfter": serialize.iso8601_datetime(created_after), + "createdBefore": serialize.iso8601_datetime(created_before), + "Accept-Encoding": accept_encoding, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ObservationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ObservationPage: + """ + Retrieve a specific page of ObservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ObservationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ObservationPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ObservationPage: + """ + Asynchronously retrieve a specific page of ObservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ObservationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ObservationPage(self._version, response, solution=self._solution) + + def get(self, observation_id: str) -> ObservationContext: + """ + Constructs a ObservationContext + + :param observation_id: The observation ID. + """ + return ObservationContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=observation_id, + ) + + def __call__(self, observation_id: str) -> ObservationContext: + """ + Constructs a ObservationContext + + :param observation_id: The observation ID. + """ + return ObservationContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=observation_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/operation.py b/twilio/rest/memory/v1/operation.py new file mode 100644 index 0000000000..b8faac294a --- /dev/null +++ b/twilio/rest/memory/v1/operation.py @@ -0,0 +1,279 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.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 OperationInstance(InstanceResource): + """ + :ivar operation_id: The unique identifier for this operation. + :ivar status: The current status of the operation. + :ivar created_at: When the operation was created. + :ivar status_url: URI to check operation status. + :ivar completed_at: When the operation completed or failed. + :ivar result: + :ivar error: + :ivar result_url: URL to fetch the resulting resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + operation_id: Optional[str] = None, + ): + super().__init__(version) + + self.operation_id: Optional[str] = payload.get("operationId") + self.status: Optional["OperationInstance.str"] = payload.get("status") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.status_url: Optional[str] = payload.get("statusUrl") + self.completed_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("completedAt") + ) + self.result: Optional[str] = payload.get("result") + self.error: Optional[str] = payload.get("error") + self.result_url: Optional[str] = payload.get("resultUrl") + + # Only set _solution if path params are provided (not None) + if operation_id is not None: + self._solution = { + "operation_id": operation_id, + } + + self._context: Optional[OperationContext] = None + + @property + def _proxy(self) -> "OperationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperationContext for this OperationInstance + """ + if self._context is None: + self._context = OperationContext( + self._version, + operation_id=self._solution["operation_id"], + ) + return self._context + + def fetch(self) -> "OperationInstance": + """ + Fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperationInstance": + """ + Asynchronous coroutine to fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 OperationContext(InstanceContext): + + def __init__(self, version: Version, operation_id: str): + """ + Initialize the OperationContext + + :param version: Version that contains the resource + :param operation_id: The operation ID returned from a write endpoint. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "operation_id": operation_id, + } + self._uri = "/ControlPlane/Operations/{operation_id}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OperationInstance: + """ + Fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + payload, _, _ = self._fetch() + return OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OperationInstance: + """ + Asynchronous coroutine to fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + payload, _, _ = await self._fetch_async() + return OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 OperationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, operation_id: str) -> OperationContext: + """ + Constructs a OperationContext + + :param operation_id: The operation ID returned from a write endpoint. + """ + return OperationContext(self._version, operation_id=operation_id) + + def __call__(self, operation_id: str) -> OperationContext: + """ + Constructs a OperationContext + + :param operation_id: The operation ID returned from a write endpoint. + """ + return OperationContext(self._version, operation_id=operation_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/profile.py b/twilio/rest/memory/v1/profile.py new file mode 100644 index 0000000000..01b1080902 --- /dev/null +++ b/twilio/rest/memory/v1/profile.py @@ -0,0 +1,1172 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ProfileInstance(InstanceResource): + """ + :ivar profiles: + :ivar meta: + :ivar message: + :ivar id: The canonical profile ID. + :ivar created_at: The time the profile was created. + :ivar traits: Multiple trait groups. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: str, + profile_id: Optional[str] = None, + ): + super().__init__(version) + + self.profiles: Optional[List[str]] = payload.get("profiles") + self.meta: Optional[ProfilesMeta] = payload.get("meta") + self.message: Optional[str] = payload.get("message") + self.id: Optional[str] = payload.get("id") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.traits: Optional[Dict[str, Dict[str, object]]] = payload.get("traits") + + # Only set _solution if path params are provided (not None) + if store_id is not None or profile_id is not None: + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + + self._context: Optional[ProfileContext] = None + + @property + def _proxy(self) -> "ProfileContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ProfileContext for this ProfileInstance + """ + if self._context is None: + self._context = ProfileContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ProfileInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ProfileInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ProfileInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ProfileInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch( + self, trait_groups: Union[str, object] = values.unset + ) -> "ProfileInstance": + """ + Fetch the ProfileInstance + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: The fetched ProfileInstance + """ + return self._proxy.fetch( + trait_groups=trait_groups, + ) + + async def fetch_async( + self, trait_groups: Union[str, object] = values.unset + ) -> "ProfileInstance": + """ + Asynchronous coroutine to fetch the ProfileInstance + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: The fetched ProfileInstance + """ + return await self._proxy.fetch_async( + trait_groups=trait_groups, + ) + + def fetch_with_http_info( + self, trait_groups: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the ProfileInstance with HTTP info + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + trait_groups=trait_groups, + ) + + async def fetch_with_http_info_async( + self, trait_groups: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ProfileInstance with HTTP info + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + trait_groups=trait_groups, + ) + + def patch(self, profile_patch: ProfilePatch) -> "ProfileInstance": + """ + Patch the ProfileInstance + + :param profile_patch: + + :returns: The patched ProfileInstance + """ + return self._proxy.patch( + profile_patch=profile_patch, + ) + + async def patch_async(self, profile_patch: ProfilePatch) -> "ProfileInstance": + """ + Asynchronous coroutine to patch the ProfileInstance + + :param profile_patch: + + :returns: The patched ProfileInstance + """ + return await self._proxy.patch_async( + profile_patch=profile_patch, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ProfileContext(InstanceContext): + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the ProfileContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ProfileInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ProfileInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ProfileInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ProfileInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self, trait_groups: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "traitGroups": trait_groups, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch(self, trait_groups: Union[str, object] = values.unset) -> ProfileInstance: + """ + Fetch the ProfileInstance + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: The fetched ProfileInstance + """ + payload, _, _ = self._fetch(trait_groups=trait_groups) + return ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def fetch_with_http_info( + self, trait_groups: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the ProfileInstance and return response metadata + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(trait_groups=trait_groups) + instance = ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, trait_groups: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "traitGroups": trait_groups, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + async def fetch_async( + self, trait_groups: Union[str, object] = values.unset + ) -> ProfileInstance: + """ + Asynchronous coroutine to fetch the ProfileInstance + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: The fetched ProfileInstance + """ + payload, _, _ = await self._fetch_async(trait_groups=trait_groups) + return ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + async def fetch_with_http_info_async( + self, trait_groups: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ProfileInstance and return response metadata + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + trait_groups=trait_groups + ) + instance = ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch(self, profile_patch: ProfilePatch) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = profile_patch.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch(self, profile_patch: ProfilePatch) -> ProfileInstance: + """ + Patch the ProfileInstance + + :param profile_patch: + + :returns: The patched ProfileInstance + """ + payload, _, _ = self._patch(profile_patch=profile_patch) + return ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def patch_with_http_info(self, profile_patch: ProfilePatch) -> ApiResponse: + """ + Patch the ProfileInstance and return response metadata + + :param profile_patch: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch(profile_patch=profile_patch) + instance = ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async(self, profile_patch: ProfilePatch) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = profile_patch.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async(self, profile_patch: ProfilePatch) -> ProfileInstance: + """ + Asynchronous coroutine to patch the ProfileInstance + + :param profile_patch: + + :returns: The patched ProfileInstance + """ + payload, _, _ = await self._patch_async(profile_patch=profile_patch) + return ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + async def patch_with_http_info_async( + self, profile_patch: ProfilePatch + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the ProfileInstance and return response metadata + + :param profile_patch: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + profile_patch=profile_patch + ) + instance = ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 ProfilePage(TokenPagination): + + def get_instance(self, payload: str) -> str: + """ + Build an instance of str + + :param payload: Payload response from the API + """ + + return payload # Return string ID directly + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ProfileList(ListResource): + + class ProfileData(object): + """ + :ivar traits: Multiple trait groups. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.traits: Optional[Dict[str, Dict[str, object]]] = payload.get("traits") + + def to_dict(self): + return { + "traits": self.traits, + } + + class ProfilePatch(object): + """ + :ivar traits: Multiple trait groups. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.traits: Optional[Dict[str, Dict[str, object]]] = payload.get("traits") + + def to_dict(self): + return { + "traits": self.traits, + } + + class ProfilesMeta(object): + """ + :ivar key: The key of the list property contains the actual data items. This enables programmatic iteration over paginated results. + :ivar page_size: + :ivar next_token: + :ivar previous_token: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.page_size: Optional[int] = payload.get("pageSize") + self.next_token: Optional[str] = payload.get("nextToken") + self.previous_token: Optional[str] = payload.get("previousToken") + + def to_dict(self): + return { + "key": self.key, + "pageSize": self.page_size, + "nextToken": self.next_token, + "previousToken": self.previous_token, + } + + def __init__(self, version: Version, store_id: str): + """ + Initialize the ProfileList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/Stores/{store_id}/Profiles".format(**self._solution) + + def _create(self, profile_data: ProfileData) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = profile_data.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, profile_data: ProfileData) -> ProfileInstance: + """ + Create the ProfileInstance + + :param profile_data: + + :returns: The created ProfileInstance + """ + payload, _, _ = self._create(profile_data=profile_data) + return ProfileInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def create_with_http_info(self, profile_data: ProfileData) -> ApiResponse: + """ + Create the ProfileInstance and return response metadata + + :param profile_data: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(profile_data=profile_data) + instance = ProfileInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, profile_data: ProfileData) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = profile_data.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, profile_data: ProfileData) -> ProfileInstance: + """ + Asynchronously create the ProfileInstance + + :param profile_data: + + :returns: The created ProfileInstance + """ + payload, _, _ = await self._create_async(profile_data=profile_data) + return ProfileInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + async def create_with_http_info_async( + self, profile_data: ProfileData + ) -> ApiResponse: + """ + Asynchronously create the ProfileInstance and return response metadata + + :param profile_data: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + profile_data=profile_data + ) + instance = ProfileInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ProfileInstance]: + """ + Streams ProfileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ProfileInstance]: + """ + Asynchronously streams ProfileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ProfileInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ProfileInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[str]: + """ + Lists ProfileInstance IDs 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: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[str]: + """ + Asynchronously lists ProfileInstance IDs 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: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ProfileInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ProfileInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> ProfilePage: + """ + Retrieve a single page of ProfileInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of ProfileInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ProfilePage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> ProfilePage: + """ + Asynchronously retrieve a single page of ProfileInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of ProfileInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ProfilePage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ProfilePage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ProfilePage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ProfilePage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ProfilePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ProfilePage: + """ + Retrieve a specific page of ProfileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ProfileInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ProfilePage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ProfilePage: + """ + Asynchronously retrieve a specific page of ProfileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ProfileInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ProfilePage(self._version, response, solution=self._solution) + + def get(self, profile_id: str) -> ProfileContext: + """ + Constructs a ProfileContext + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + """ + return ProfileContext( + self._version, store_id=self._solution["store_id"], profile_id=profile_id + ) + + def __call__(self, profile_id: str) -> ProfileContext: + """ + Constructs a ProfileContext + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + """ + return ProfileContext( + self._version, store_id=self._solution["store_id"], profile_id=profile_id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/recall.py b/twilio/rest/memory/v1/recall.py new file mode 100644 index 0000000000..5258e3eb09 --- /dev/null +++ b/twilio/rest/memory/v1/recall.py @@ -0,0 +1,382 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class RecallInstance(InstanceResource): + + class ParticipantType(object): + HUMAN_AGENT = "HUMAN_AGENT" + CUSTOMER = "CUSTOMER" + AI_AGENT = "AI_AGENT" + AGENT = "AGENT" + UNKNOWN = "UNKNOWN" + + """ + :ivar observations: Array of observation memories. + :ivar summaries: Array of summary memories derived from observations at the end of conversations. + :ivar communications: Array of recent communication context. + :ivar meta: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], store_id: str, profile_id: str + ): + super().__init__(version) + + self.observations: Optional[List[str]] = payload.get("observations") + self.summaries: Optional[List[str]] = payload.get("summaries") + self.communications: Optional[List[str]] = payload.get("communications") + self.meta: Optional[str] = payload.get("meta") + + # Only set _solution if path params are provided (not None) + if store_id is not None or profile_id is not None: + self._solution = { + "store_id": store_id, + "profile_id": profile_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 RecallList(ListResource): + + class CommunicationContent(object): + """ + :ivar text: Primary text content (optional). + """ + + def __init__(self, payload: Dict[str, Any]): + + self.text: Optional[str] = payload.get("text") + + def to_dict(self): + return { + "text": self.text, + } + + class CommunicationRecipients(object): + """ + :ivar id: Participant identifier. + :ivar name: Participant display name + :ivar type: + :ivar profile_id: The canonical profile ID. + :ivar address: Address of the Participant (e.g., phone number, email address) + :ivar channel: The channel on which the message originated + :ivar delivery_status: Delivery status of the Communication to this recipient + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.type: Optional[ParticipantType] = payload.get("type") + self.profile_id: Optional[str] = payload.get("profileId") + self.address: Optional[str] = payload.get("address") + self.channel: Optional[str] = payload.get("channel") + self.delivery_status: Optional[str] = payload.get("deliveryStatus") + + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "type": self.type.to_dict() if self.type is not None else None, + "profileId": self.profile_id, + "address": self.address, + "channel": self.channel, + "deliveryStatus": self.delivery_status, + } + + class MemoryRetrievalRequest(object): + """ + :ivar conversation_id: A unique identifier for the conversation using Twilio Type ID (TTID) format. + :ivar query: Hybrid search query for finding relevant memories. Omit to use query expansion to generate query from previous 10 communications in conversation. + :ivar begin_date: Start date for filtering memories (inclusive). + :ivar end_date: End date for filtering memories (exclusive). + :ivar communications_limit: Maximum number of conversational session memories to return. If omitted or set to 0, no session memories will be fetched. + :ivar observations_limit: Maximum number of observation memories to return. If omitted, defaults to 20. If set to 0, no observation memories will be fetched. + :ivar summaries_limit: Maximum number of summary memories to return. If omitted, defaults to 5. If set to 0, no summary memories will be fetched. + :ivar relevance_threshold: Minimum relevance score threshold for observations and summaries to be returned. Only memories with a relevance score greater than or equal to this threshold will be included in the response. This threshold only applies when results are ranked by relevance. When results are returned in most-recent order, this field has no effect. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.conversation_id: Optional[str] = payload.get("conversationId") + self.query: Optional[str] = payload.get("query") + self.begin_date: Optional[datetime] = payload.get("beginDate") + self.end_date: Optional[datetime] = payload.get("endDate") + self.communications_limit: Optional[int] = payload.get( + "communicationsLimit" + ) + self.observations_limit: Optional[int] = payload.get("observationsLimit") + self.summaries_limit: Optional[int] = payload.get("summariesLimit") + self.relevance_threshold: Optional[float] = payload.get( + "relevanceThreshold" + ) + + def to_dict(self): + return { + "conversationId": self.conversation_id, + "query": self.query, + "beginDate": self.begin_date, + "endDate": self.end_date, + "communicationsLimit": self.communications_limit, + "observationsLimit": self.observations_limit, + "summariesLimit": self.summaries_limit, + "relevanceThreshold": self.relevance_threshold, + } + + class Participant(object): + """ + :ivar id: Participant identifier. + :ivar name: Participant display name + :ivar type: + :ivar profile_id: The canonical profile ID. + :ivar address: Address of the Participant (e.g., phone number, email address) + :ivar channel: The channel on which the message originated + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.type: Optional[ParticipantType] = payload.get("type") + self.profile_id: Optional[str] = payload.get("profileId") + self.address: Optional[str] = payload.get("address") + self.channel: Optional[str] = payload.get("channel") + + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "type": self.type.to_dict() if self.type is not None else None, + "profileId": self.profile_id, + "address": self.address, + "channel": self.channel, + } + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the RecallList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/Recall".format( + **self._solution + ) + + def _create( + self, + memory_retrieval_request: MemoryRetrievalRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = memory_retrieval_request.to_dict() + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Encoding": content_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + memory_retrieval_request: MemoryRetrievalRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> RecallInstance: + """ + Create the RecallInstance + + :param memory_retrieval_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: The created RecallInstance + """ + payload, _, _ = self._create( + memory_retrieval_request=memory_retrieval_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + return RecallInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def create_with_http_info( + self, + memory_retrieval_request: MemoryRetrievalRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the RecallInstance and return response metadata + + :param memory_retrieval_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + memory_retrieval_request=memory_retrieval_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + instance = RecallInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + memory_retrieval_request: MemoryRetrievalRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = memory_retrieval_request.to_dict() + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Encoding": content_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + memory_retrieval_request: MemoryRetrievalRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> RecallInstance: + """ + Asynchronously create the RecallInstance + + :param memory_retrieval_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: The created RecallInstance + """ + payload, _, _ = await self._create_async( + memory_retrieval_request=memory_retrieval_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + return RecallInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + async def create_with_http_info_async( + self, + memory_retrieval_request: MemoryRetrievalRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the RecallInstance and return response metadata + + :param memory_retrieval_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + memory_retrieval_request=memory_retrieval_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + instance = RecallInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/revision.py b/twilio/rest/memory/v1/revision.py new file mode 100644 index 0000000000..84b8a13a69 --- /dev/null +++ b/twilio/rest/memory/v1/revision.py @@ -0,0 +1,592 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class RevisionInstance(InstanceResource): + """ + :ivar content: The main content of the observation. + :ivar occurred_at: The timestamp when the observation originally occurred. + :ivar source: The source system that generated this observation. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :ivar conversation_ids: Array of conversation IDs associated with this observation. + :ivar id: A unique identifier for the observation using Twilio Type ID (TTID) format. + :ivar created_at: The timestamp when the observation was created. + :ivar updated_at: The timestamp when the observation was last updated. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + store_id: str, + profile_id: str, + observation_id: str, + ): + super().__init__(version) + + self.content: Optional[str] = payload.get("content") + self.occurred_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("occurredAt") + ) + self.source: Optional[str] = payload.get("source") + self.conversation_ids: Optional[List[str]] = payload.get("conversationIds") + self.id: Optional[str] = payload.get("id") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + + # Only set _solution if path params are provided (not None) + if store_id is not None or profile_id is not None or observation_id is not None: + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "observation_id": observation_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 RevisionPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> RevisionInstance: + """ + Build an instance of RevisionInstance + + :param payload: Payload response from the API + """ + + return RevisionInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RevisionList(ListResource): + + def __init__( + self, version: Version, store_id: str, profile_id: str, observation_id: str + ): + """ + Initialize the RevisionList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + :param observation_id: The observation ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "observation_id": observation_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/Observations/{observation_id}/Revisions".format( + **self._solution + ) + + def stream( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RevisionInstance]: + """ + Streams RevisionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RevisionInstance]: + """ + Asynchronously streams RevisionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RevisionInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RevisionInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RevisionInstance]: + """ + Lists RevisionInstance 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: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RevisionInstance]: + """ + Asynchronously lists RevisionInstance 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: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RevisionInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RevisionInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + ) -> RevisionPage: + """ + Retrieve a single page of RevisionInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :returns: Page of RevisionInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "Accept-Encoding": accept_encoding, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RevisionPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + ) -> RevisionPage: + """ + Asynchronously retrieve a single page of RevisionInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :returns: Page of RevisionInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "Accept-Encoding": accept_encoding, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RevisionPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + accept_encoding: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RevisionPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "Accept-Encoding": accept_encoding, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RevisionPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + accept_encoding: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RevisionPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "Accept-Encoding": accept_encoding, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RevisionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> RevisionPage: + """ + Retrieve a specific page of RevisionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RevisionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RevisionPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> RevisionPage: + """ + Asynchronously retrieve a specific page of RevisionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RevisionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RevisionPage(self._version, response, solution=self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/store.py b/twilio/rest/memory/v1/store.py new file mode 100644 index 0000000000..c617301a0e --- /dev/null +++ b/twilio/rest/memory/v1/store.py @@ -0,0 +1,1149 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class StoreInstance(InstanceResource): + """ + :ivar stores: List of Memory Store IDs associated with the Twilio account. + :ivar meta: + :ivar message: + :ivar status_url: URI to check operation status. + :ivar display_name: Provides a unique and addressable name to be assigned to this Store. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + :ivar description: A human readable description of this resource, up to 128 characters. + :ivar id: The unique identifier for the Memory Store + :ivar status: The current status of the Memory Store. A store begins in the QUEUED state as it is scheduled for processing. It then moves to PROVISIONING at the beginning of processing. It transitions to ACTIVE once all dependent resources are provisioned, including Conversational Intelligence capabilities. If there is an issue provisioning resources, the store will move to the FAILED state. + :ivar intelligence_service_id: The ID of the associated intelligence service that was provisioned for memory extraction. + :ivar version: The current version number of the Memory Store. Incremented on each successful update. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: Optional[str] = None, + ): + super().__init__(version) + + self.stores: Optional[List[str]] = payload.get("stores") + self.meta: Optional[Meta] = payload.get("meta") + self.message: Optional[str] = payload.get("message") + self.status_url: Optional[str] = payload.get("statusUrl") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.status: Optional["StoreInstance.str"] = payload.get("status") + self.intelligence_service_id: Optional[str] = payload.get( + "intelligenceServiceId" + ) + self.version: Optional[int] = deserialize.integer(payload.get("version")) + + # Only set _solution if path params are provided (not None) + if store_id is not None: + self._solution = { + "store_id": store_id, + } + + self._context: Optional[StoreContext] = None + + @property + def _proxy(self) -> "StoreContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: StoreContext for this StoreInstance + """ + if self._context is None: + self._context = StoreContext( + self._version, + store_id=self._solution["store_id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the StoreInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the StoreInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the StoreInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the StoreInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "StoreInstance": + """ + Fetch the StoreInstance + + + :returns: The fetched StoreInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "StoreInstance": + """ + Asynchronous coroutine to fetch the StoreInstance + + + :returns: The fetched StoreInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the StoreInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the StoreInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def patch( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> "StoreInstance": + """ + Patch the StoreInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_store_request: + + :returns: The patched StoreInstance + """ + return self._proxy.patch( + if_match=if_match, + patch_store_request=patch_store_request, + ) + + async def patch_async( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> "StoreInstance": + """ + Asynchronous coroutine to patch the StoreInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_store_request: + + :returns: The patched StoreInstance + """ + return await self._proxy.patch_async( + if_match=if_match, + patch_store_request=patch_store_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 StoreContext(InstanceContext): + + def __init__(self, version: Version, store_id: str): + """ + Initialize the StoreContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/ControlPlane/Stores/{store_id}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the StoreInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the StoreInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the StoreInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the StoreInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> StoreInstance: + """ + Fetch the StoreInstance + + + :returns: The fetched StoreInstance + """ + payload, _, _ = self._fetch() + return StoreInstance( + self._version, + payload, + store_id=self._solution["store_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the StoreInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = StoreInstance( + self._version, + payload, + store_id=self._solution["store_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> StoreInstance: + """ + Asynchronous coroutine to fetch the StoreInstance + + + :returns: The fetched StoreInstance + """ + payload, _, _ = await self._fetch_async() + return StoreInstance( + self._version, + payload, + store_id=self._solution["store_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the StoreInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = StoreInstance( + self._version, + payload, + store_id=self._solution["store_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = patch_store_request.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["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> StoreInstance: + """ + Patch the StoreInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_store_request: + + :returns: The patched StoreInstance + """ + payload, _, _ = self._patch( + if_match=if_match, patch_store_request=patch_store_request + ) + return StoreInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def patch_with_http_info( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> ApiResponse: + """ + Patch the StoreInstance and return response metadata + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_store_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch( + if_match=if_match, patch_store_request=patch_store_request + ) + instance = StoreInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = patch_store_request.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["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> StoreInstance: + """ + Asynchronous coroutine to patch the StoreInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_store_request: + + :returns: The patched StoreInstance + """ + payload, _, _ = await self._patch_async( + if_match=if_match, patch_store_request=patch_store_request + ) + return StoreInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + async def patch_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the StoreInstance and return response metadata + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_store_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + if_match=if_match, patch_store_request=patch_store_request + ) + instance = StoreInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 StorePage(TokenPagination): + + def get_instance(self, payload: str) -> str: + """ + Build an instance of str + + :param payload: Payload response from the API + """ + + return payload # Return string ID directly + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class StoreList(ListResource): + + class Meta(object): + """ + :ivar key: The key of the list property contains the actual data items. This enables programmatic iteration over paginated results. + :ivar page_size: + :ivar next_token: + :ivar previous_token: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.page_size: Optional[int] = payload.get("pageSize") + self.next_token: Optional[str] = payload.get("nextToken") + self.previous_token: Optional[str] = payload.get("previousToken") + + def to_dict(self): + return { + "key": self.key, + "pageSize": self.page_size, + "nextToken": self.next_token, + "previousToken": self.previous_token, + } + + class PatchStoreRequest(object): + """ + :ivar display_name: Provides a unique and addressable name to be assigned to this Store. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + :ivar description: A human readable description of this resource, up to 128 characters. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + } + + class ServiceRequest(object): + """ + :ivar display_name: Provides a unique and addressable name to be assigned to this Store. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + :ivar description: A human readable description of this resource, up to 128 characters. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + } + + def __init__(self, version: Version): + """ + Initialize the StoreList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ControlPlane/Stores" + + def _create(self, service_request: ServiceRequest) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = service_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, service_request: ServiceRequest) -> StoreInstance: + """ + Create the StoreInstance + + :param service_request: + + :returns: The created StoreInstance + """ + payload, _, _ = self._create(service_request=service_request) + return StoreInstance(self._version, payload) + + def create_with_http_info(self, service_request: ServiceRequest) -> ApiResponse: + """ + Create the StoreInstance and return response metadata + + :param service_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(service_request=service_request) + instance = StoreInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, service_request: ServiceRequest) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = service_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, service_request: ServiceRequest) -> StoreInstance: + """ + Asynchronously create the StoreInstance + + :param service_request: + + :returns: The created StoreInstance + """ + payload, _, _ = await self._create_async(service_request=service_request) + return StoreInstance(self._version, payload) + + async def create_with_http_info_async( + self, service_request: ServiceRequest + ) -> ApiResponse: + """ + Asynchronously create the StoreInstance and return response metadata + + :param service_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + service_request=service_request + ) + instance = StoreInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[StoreInstance]: + """ + Streams StoreInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[StoreInstance]: + """ + Asynchronously streams StoreInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams StoreInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams StoreInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[str]: + """ + Lists StoreInstance IDs 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: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[str]: + """ + Asynchronously lists StoreInstance IDs 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: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists StoreInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists StoreInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> StorePage: + """ + Retrieve a single page of StoreInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of StoreInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return StorePage(self._version, response, uri=self._uri, params=data) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> StorePage: + """ + Asynchronously retrieve a single page of StoreInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of StoreInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return StorePage(self._version, response, uri=self._uri, params=data) + + def page_with_http_info( + self, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with StorePage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = StorePage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with StorePage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = StorePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> StorePage: + """ + Retrieve a specific page of StoreInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of StoreInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return StorePage(self._version, response) + + async def get_page_async(self, target_url: str) -> StorePage: + """ + Asynchronously retrieve a specific page of StoreInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of StoreInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return StorePage(self._version, response) + + def get(self, store_id: str) -> StoreContext: + """ + Constructs a StoreContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return StoreContext(self._version, store_id=store_id) + + def __call__(self, store_id: str) -> StoreContext: + """ + Constructs a StoreContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return StoreContext(self._version, store_id=store_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/trait.py b/twilio/rest/memory/v1/trait.py new file mode 100644 index 0000000000..b565d8066c --- /dev/null +++ b/twilio/rest/memory/v1/trait.py @@ -0,0 +1,587 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class TraitInstance(InstanceResource): + """ + :ivar name: The name of the trait. + :ivar value: The value of a trait. Can be a string, integer, boolean, or an array of these types (arrays cannot contain nested arrays). + :ivar trait_group: The trait group name to which this trait belongs. + :ivar timestamp: The time the trait was created or last updated. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], store_id: str, profile_id: str + ): + super().__init__(version) + + self.name: Optional[str] = payload.get("name") + self.value: Optional[Dict[str, object]] = payload.get("value") + self.trait_group: Optional[str] = payload.get("traitGroup") + self.timestamp: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("timestamp") + ) + + # Only set _solution if path params are provided (not None) + if store_id is not None or profile_id is not None: + self._solution = { + "store_id": store_id, + "profile_id": profile_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 TraitPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> TraitInstance: + """ + Build an instance of TraitInstance + + :param payload: Payload response from the API + """ + + return TraitInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TraitList(ListResource): + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the TraitList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/Traits".format( + **self._solution + ) + + def stream( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TraitInstance]: + """ + Streams TraitInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TraitInstance]: + """ + Asynchronously streams TraitInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TraitInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TraitInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TraitInstance]: + """ + Lists TraitInstance 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: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TraitInstance]: + """ + Asynchronously lists TraitInstance 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: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TraitInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TraitInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + ) -> TraitPage: + """ + Retrieve a single page of TraitInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param trait_groups: Comma separated list of trait group names to include. + :returns: Page of TraitInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + "traitGroups": trait_groups, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TraitPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + ) -> TraitPage: + """ + Asynchronously retrieve a single page of TraitInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param trait_groups: Comma separated list of trait group names to include. + :returns: Page of TraitInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + "traitGroups": trait_groups, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TraitPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param trait_groups: Comma separated list of trait group names to include. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TraitPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "traitGroups": trait_groups, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TraitPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param trait_groups: Comma separated list of trait group names to include. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TraitPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "traitGroups": trait_groups, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TraitPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> TraitPage: + """ + Retrieve a specific page of TraitInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TraitInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TraitPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> TraitPage: + """ + Asynchronously retrieve a specific page of TraitInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TraitInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TraitPage(self._version, response, solution=self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/trait_group.py b/twilio/rest/memory/v1/trait_group.py new file mode 100644 index 0000000000..5cf1c5d276 --- /dev/null +++ b/twilio/rest/memory/v1/trait_group.py @@ -0,0 +1,1535 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class TraitGroupInstance(InstanceResource): + """ + :ivar trait_group: + :ivar meta: + :ivar message: + :ivar status_url: URI to check operation status. + :ivar display_name: Provides a unique and addressable name to be assigned to this Trait Group + :ivar description: description of the Trait Group + :ivar traits: Map of traits that are part of this Trait Group, where the key is the trait name and the value is the trait's definition. + :ivar version: The current version number of the Trait Group. Incremented on each successful update. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: str, + trait_group_name: Optional[str] = None, + ): + super().__init__(version) + + self.trait_group: Optional[TraitGroup] = payload.get("traitGroup") + self.meta: Optional[Meta] = payload.get("meta") + self.message: Optional[str] = payload.get("message") + self.status_url: Optional[str] = payload.get("statusUrl") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.traits: Optional[Dict[str, TraitGroupCoreTraitsValue]] = payload.get( + "traits" + ) + self.version: Optional[int] = deserialize.integer(payload.get("version")) + + # Only set _solution if path params are provided (not None) + if store_id is not None or trait_group_name is not None: + self._solution = { + "store_id": store_id, + "trait_group_name": trait_group_name, + } + + self._context: Optional[TraitGroupContext] = None + + @property + def _proxy(self) -> "TraitGroupContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TraitGroupContext for this TraitGroupInstance + """ + if self._context is None: + self._context = TraitGroupContext( + self._version, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TraitGroupInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TraitGroupInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TraitGroupInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TraitGroupInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> "TraitGroupInstance": + """ + Fetch the TraitGroupInstance + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: The fetched TraitGroupInstance + """ + return self._proxy.fetch( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + + async def fetch_async( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> "TraitGroupInstance": + """ + Asynchronous coroutine to fetch the TraitGroupInstance + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: The fetched TraitGroupInstance + """ + return await self._proxy.fetch_async( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + + def fetch_with_http_info( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the TraitGroupInstance with HTTP info + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + + async def fetch_with_http_info_async( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TraitGroupInstance with HTTP info + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + + def patch( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> "TraitGroupInstance": + """ + Patch the TraitGroupInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_trait_group_request: + + :returns: The patched TraitGroupInstance + """ + return self._proxy.patch( + if_match=if_match, + patch_trait_group_request=patch_trait_group_request, + ) + + async def patch_async( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> "TraitGroupInstance": + """ + Asynchronous coroutine to patch the TraitGroupInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_trait_group_request: + + :returns: The patched TraitGroupInstance + """ + return await self._proxy.patch_async( + if_match=if_match, + patch_trait_group_request=patch_trait_group_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 TraitGroupContext(InstanceContext): + + def __init__(self, version: Version, store_id: str, trait_group_name: str): + """ + Initialize the TraitGroupContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param trait_group_name: A unique Name of the TraitGroup + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "trait_group_name": trait_group_name, + } + self._uri = ( + "/ControlPlane/Stores/{store_id}/TraitGroups/{trait_group_name}".format( + **self._solution + ) + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the TraitGroupInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TraitGroupInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TraitGroupInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TraitGroupInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "includeTraits": serialize.boolean_to_string(include_traits), + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> TraitGroupInstance: + """ + Fetch the TraitGroupInstance + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: The fetched TraitGroupInstance + """ + payload, _, _ = self._fetch( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + return TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + + def fetch_with_http_info( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the TraitGroupInstance and return response metadata + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + instance = TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "includeTraits": serialize.boolean_to_string(include_traits), + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + async def fetch_async( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> TraitGroupInstance: + """ + Asynchronous coroutine to fetch the TraitGroupInstance + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: The fetched TraitGroupInstance + """ + payload, _, _ = await self._fetch_async( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + return TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + + async def fetch_with_http_info_async( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TraitGroupInstance and return response metadata + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + instance = TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = patch_trait_group_request.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["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> TraitGroupInstance: + """ + Patch the TraitGroupInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_trait_group_request: + + :returns: The patched TraitGroupInstance + """ + payload, _, _ = self._patch( + if_match=if_match, patch_trait_group_request=patch_trait_group_request + ) + return TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + + def patch_with_http_info( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> ApiResponse: + """ + Patch the TraitGroupInstance and return response metadata + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch( + if_match=if_match, patch_trait_group_request=patch_trait_group_request + ) + instance = TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = patch_trait_group_request.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["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> TraitGroupInstance: + """ + Asynchronous coroutine to patch the TraitGroupInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_trait_group_request: + + :returns: The patched TraitGroupInstance + """ + payload, _, _ = await self._patch_async( + if_match=if_match, patch_trait_group_request=patch_trait_group_request + ) + return TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + + async def patch_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the TraitGroupInstance and return response metadata + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + if_match=if_match, patch_trait_group_request=patch_trait_group_request + ) + instance = TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 TraitGroupPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> TraitGroupInstance: + """ + Build an instance of TraitGroupInstance + + :param payload: Payload response from the API + """ + + return TraitGroupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TraitGroupList(ListResource): + + class Meta(object): + """ + :ivar key: The key of the list property contains the actual data items. This enables programmatic iteration over paginated results. + :ivar page_size: + :ivar next_token: + :ivar previous_token: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.page_size: Optional[int] = payload.get("pageSize") + self.next_token: Optional[str] = payload.get("nextToken") + self.previous_token: Optional[str] = payload.get("previousToken") + + def to_dict(self): + return { + "key": self.key, + "pageSize": self.page_size, + "nextToken": self.next_token, + "previousToken": self.previous_token, + } + + class PatchTraitGroupRequest(object): + """ + :ivar description: Updated description of the Trait Group + :ivar traits: Map of traits to add, update, or remove in this Trait Group, where the key is the trait name. - To update/add a trait: provide the complete TraitDefinition object - To remove a trait: set dataType to an empty string (\"\") + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.traits: Optional[Dict[str, TraitDefinition]] = payload.get("traits") + + def to_dict(self): + return { + "description": self.description, + "traits": ( + {k: v.to_dict() for k, v in self.traits.items()} + if self.traits is not None + else None + ), + } + + class TraitDefinition(object): + """ + :ivar data_type: Data type of the Trait, such as STRING, NUMBER, BOOLEAN, ARRAY. For DELETE operations in PATCH requests, set this to an empty string (\"\") to mark the trait for deletion. + :ivar description: Description of the Trait, providing additional context or information. + :ivar id_type_promotion: The name of the identifier type to promote the trait value to, such as ''email'', ''phone'', ''user_id'', etc. This allows the trait to be mapped to an identifier in Identity Resolution. The identifier type should be configured in the Identity Resolution Settings. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.data_type: Optional[str] = payload.get("dataType") + self.description: Optional[str] = payload.get("description") + self.id_type_promotion: Optional[str] = payload.get("idTypePromotion") + + def to_dict(self): + return { + "dataType": self.data_type, + "description": self.description, + "idTypePromotion": self.id_type_promotion, + } + + class TraitGroup(object): + """ + :ivar display_name: Provides a unique and addressable name to be assigned to this Trait Group + :ivar description: description of the Trait Group + :ivar traits: Map of traits that are part of this Trait Group, where the key is the trait name and the value is the trait's definition. + :ivar version: The current version number of the Trait Group. Incremented on each successful update. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.traits: Optional[Dict[str, TraitGroupCoreTraitsValue]] = payload.get( + "traits" + ) + self.version: Optional[int] = deserialize.integer(payload.get("version")) + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "traits": ( + {k: v.to_dict() for k, v in self.traits.items()} + if self.traits is not None + else None + ), + "version": self.version, + } + + class TraitGroupCoreTraitsValue(object): + """ + :ivar data_type: Data type of the Trait, such as STRING, NUMBER, BOOLEAN, ARRAY. For DELETE operations in PATCH requests, set this to an empty string (\"\") to mark the trait for deletion. + :ivar description: Description of the Trait, providing additional context or information. + :ivar validation_rule: + :ivar id_type_promotion: The name of the identifier type to promote the trait value to, such as ''email'', ''phone'', ''user_id'', etc. This allows the trait to be mapped to an identifier in Identity Resolution. The identifier type should be configured in the Identity Resolution Settings. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.data_type: Optional[str] = payload.get("dataType") + self.description: Optional[str] = payload.get("description") + self.validation_rule: Optional[ValidationRule] = payload.get( + "validationRule" + ) + self.id_type_promotion: Optional[str] = payload.get("idTypePromotion") + + def to_dict(self): + return { + "dataType": self.data_type, + "description": self.description, + "validationRule": ( + self.validation_rule.to_dict() + if self.validation_rule is not None + else None + ), + "idTypePromotion": self.id_type_promotion, + } + + class TraitGroupRequest(object): + """ + :ivar display_name: Unique name of the Trait Group + :ivar description: description of the Trait Group + :ivar traits: Map of traits belonging to this Trait Group, keyed by trait name. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.traits: Optional[Dict[str, TraitGroupCoreTraitsValue]] = payload.get( + "traits" + ) + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "traits": ( + {k: v.to_dict() for k, v in self.traits.items()} + if self.traits is not None + else None + ), + } + + class ValidationRule(object): + """ + :ivar pattern: Regex pattern (max 1000 chars) + :ivar min_length: Minimum string length + :ivar max_length: Maximum string length + :ivar rule_type: Discriminator field indicating this is an array validation rule. + :ivar min: Minimum value + :ivar max: Maximum value + :ivar min_items: Minimum number of items + :ivar max_items: Maximum number of items + """ + + def __init__(self, payload: Dict[str, Any]): + + self.pattern: Optional[str] = payload.get("pattern") + self.min_length: Optional[int] = payload.get("minLength") + self.max_length: Optional[int] = payload.get("maxLength") + self.rule_type: Optional[str] = payload.get("ruleType") + self.min: Optional[float] = payload.get("min") + self.max: Optional[float] = payload.get("max") + self.min_items: Optional[int] = payload.get("minItems") + self.max_items: Optional[int] = payload.get("maxItems") + + def to_dict(self): + return { + "pattern": self.pattern, + "minLength": self.min_length, + "maxLength": self.max_length, + "ruleType": self.rule_type, + "min": self.min, + "max": self.max, + "minItems": self.min_items, + "maxItems": self.max_items, + } + + def __init__(self, version: Version, store_id: str): + """ + Initialize the TraitGroupList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/ControlPlane/Stores/{store_id}/TraitGroups".format( + **self._solution + ) + + def _create( + self, trait_group_request: Union[TraitGroupRequest, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = trait_group_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, trait_group_request: Union[TraitGroupRequest, object] = values.unset + ) -> TraitGroupInstance: + """ + Create the TraitGroupInstance + + :param trait_group_request: + + :returns: The created TraitGroupInstance + """ + payload, _, _ = self._create(trait_group_request=trait_group_request) + return TraitGroupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def create_with_http_info( + self, trait_group_request: Union[TraitGroupRequest, object] = values.unset + ) -> ApiResponse: + """ + Create the TraitGroupInstance and return response metadata + + :param trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + trait_group_request=trait_group_request + ) + instance = TraitGroupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, trait_group_request: Union[TraitGroupRequest, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = trait_group_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, trait_group_request: Union[TraitGroupRequest, object] = values.unset + ) -> TraitGroupInstance: + """ + Asynchronously create the TraitGroupInstance + + :param trait_group_request: + + :returns: The created TraitGroupInstance + """ + payload, _, _ = await self._create_async( + trait_group_request=trait_group_request + ) + return TraitGroupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + async def create_with_http_info_async( + self, trait_group_request: Union[TraitGroupRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the TraitGroupInstance and return response metadata + + :param trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + trait_group_request=trait_group_request + ) + instance = TraitGroupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TraitGroupInstance]: + """ + Streams TraitGroupInstance records from the API as a generator stream. + This operation lazily loads 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 include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TraitGroupInstance]: + """ + Asynchronously streams TraitGroupInstance records from the API as a generator stream. + This operation lazily loads 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 include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TraitGroupInstance and returns headers from first page + + + :param bool include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TraitGroupInstance and returns headers from first page + + + :param bool include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TraitGroupInstance]: + """ + Lists TraitGroupInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TraitGroupInstance]: + """ + Asynchronously lists TraitGroupInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TraitGroupInstance and returns headers from first page + + + :param bool include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TraitGroupInstance and returns headers from first page + + + :param bool include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> TraitGroupPage: + """ + Retrieve a single page of TraitGroupInstance records from the API. + Request is executed immediately + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of TraitGroupInstance + """ + data = values.of( + { + "includeTraits": serialize.boolean_to_string(include_traits), + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TraitGroupPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> TraitGroupPage: + """ + Asynchronously retrieve a single page of TraitGroupInstance records from the API. + Request is executed immediately + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of TraitGroupInstance + """ + data = values.of( + { + "includeTraits": serialize.boolean_to_string(include_traits), + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TraitGroupPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + include_traits: Union[bool, object] = values.unset, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param include_traits: Whether to include trait definitions in the response + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TraitGroupPage, status code, and headers + """ + data = values.of( + { + "includeTraits": serialize.boolean_to_string(include_traits), + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TraitGroupPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + include_traits: Union[bool, object] = values.unset, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param include_traits: Whether to include trait definitions in the response + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TraitGroupPage, status code, and headers + """ + data = values.of( + { + "includeTraits": serialize.boolean_to_string(include_traits), + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TraitGroupPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> TraitGroupPage: + """ + Retrieve a specific page of TraitGroupInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TraitGroupInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TraitGroupPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> TraitGroupPage: + """ + Asynchronously retrieve a specific page of TraitGroupInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TraitGroupInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TraitGroupPage(self._version, response, solution=self._solution) + + def get(self, trait_group_name: str) -> TraitGroupContext: + """ + Constructs a TraitGroupContext + + :param trait_group_name: A unique Name of the TraitGroup + """ + return TraitGroupContext( + self._version, + store_id=self._solution["store_id"], + trait_group_name=trait_group_name, + ) + + def __call__(self, trait_group_name: str) -> TraitGroupContext: + """ + Constructs a TraitGroupContext + + :param trait_group_name: A unique Name of the TraitGroup + """ + return TraitGroupContext( + self._version, + store_id=self._solution["store_id"], + trait_group_name=trait_group_name, + ) + + 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..18b7f3e1a6 --- /dev/null +++ b/twilio/rest/messaging/MessagingBase.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.messaging.v1 import V1 +from twilio.rest.messaging.v2 import V2 +from twilio.rest.messaging.v3 import V3 + + +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 + self._v3: Optional[V3] = 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 + + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Messaging + """ + 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/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..1e1100e32e 100644 --- a/twilio/rest/messaging/v1/__init__.py +++ b/twilio/rest/messaging/v1/__init__.py @@ -1,42 +1,159 @@ -# 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.domain_validate_dn import DomainValidateDnList +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._domain_validate_dns: Optional[DomainValidateDnList] = 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 domain_validate_dns(self) -> DomainValidateDnList: + if self._domain_validate_dns is None: + self._domain_validate_dns = DomainValidateDnList(self) + return self._domain_validate_dns + + @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..349d7ba4f3 --- /dev/null +++ b/twilio/rest/messaging/v1/brand_registration/__init__.py @@ -0,0 +1,1074 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BrandRegistrationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BrandRegistrationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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() + + def update_with_http_info(self) -> ApiResponse: + """ + Update the BrandRegistrationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info() + + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the BrandRegistrationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BrandRegistrationInstance: + """ + Fetch the BrandRegistrationInstance + + + :returns: The fetched BrandRegistrationInstance + """ + payload, _, _ = self._fetch() + return BrandRegistrationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BrandRegistrationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BrandRegistrationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> BrandRegistrationInstance: + """ + Asynchronous coroutine to fetch the BrandRegistrationInstance + + + :returns: The fetched BrandRegistrationInstance + """ + payload, _, _ = await self._fetch_async() + return BrandRegistrationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BrandRegistrationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BrandRegistrationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self) -> BrandRegistrationInstance: + """ + Update the BrandRegistrationInstance + + + :returns: The updated BrandRegistrationInstance + """ + payload, _, _ = self._update() + return BrandRegistrationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def update_with_http_info(self) -> ApiResponse: + """ + Update the BrandRegistrationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update() + instance = BrandRegistrationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async(self) -> BrandRegistrationInstance: + """ + Asynchronous coroutine to update the BrandRegistrationInstance + + + :returns: The updated BrandRegistrationInstance + """ + payload, _, _ = await self._update_async() + return BrandRegistrationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the BrandRegistrationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async() + instance = BrandRegistrationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + customer_profile_bundle_sid=customer_profile_bundle_sid, + a2p_profile_bundle_sid=a2p_profile_bundle_sid, + brand_type=brand_type, + mock=mock, + skip_automatic_sec_vet=skip_automatic_sec_vet, + ) + return BrandRegistrationInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the BrandRegistrationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + customer_profile_bundle_sid=customer_profile_bundle_sid, + a2p_profile_bundle_sid=a2p_profile_bundle_sid, + brand_type=brand_type, + mock=mock, + skip_automatic_sec_vet=skip_automatic_sec_vet, + ) + instance = BrandRegistrationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + customer_profile_bundle_sid=customer_profile_bundle_sid, + a2p_profile_bundle_sid=a2p_profile_bundle_sid, + brand_type=brand_type, + mock=mock, + skip_automatic_sec_vet=skip_automatic_sec_vet, + ) + return BrandRegistrationInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the BrandRegistrationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + customer_profile_bundle_sid=customer_profile_bundle_sid, + a2p_profile_bundle_sid=a2p_profile_bundle_sid, + brand_type=brand_type, + mock=mock, + skip_automatic_sec_vet=skip_automatic_sec_vet, + ) + instance = BrandRegistrationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BrandRegistrationInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BrandRegistrationInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BrandRegistrationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BrandRegistrationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BrandRegistrationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BrandRegistrationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BrandRegistrationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BrandRegistrationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..0ac2f302c5 --- /dev/null +++ b/twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py @@ -0,0 +1,170 @@ +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.api_response import ApiResponse + +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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, headers=headers + ) + + def create(self) -> BrandRegistrationOtpInstance: + """ + Create the BrandRegistrationOtpInstance + + + :returns: The created BrandRegistrationOtpInstance + """ + payload, _, _ = self._create() + return BrandRegistrationOtpInstance( + self._version, + payload, + brand_registration_sid=self._solution["brand_registration_sid"], + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the BrandRegistrationOtpInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = BrandRegistrationOtpInstance( + self._version, + payload, + brand_registration_sid=self._solution["brand_registration_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, headers=headers + ) + + async def create_async(self) -> BrandRegistrationOtpInstance: + """ + Asynchronously create the BrandRegistrationOtpInstance + + + :returns: The created BrandRegistrationOtpInstance + """ + payload, _, _ = await self._create_async() + return BrandRegistrationOtpInstance( + self._version, + payload, + brand_registration_sid=self._solution["brand_registration_sid"], + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the BrandRegistrationOtpInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = BrandRegistrationOtpInstance( + self._version, + payload, + brand_registration_sid=self._solution["brand_registration_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..9cd9243470 --- /dev/null +++ b/twilio/rest/messaging/v1/brand_registration/brand_vetting.py @@ -0,0 +1,904 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BrandVettingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BrandVettingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BrandVettingInstance: + """ + Fetch the BrandVettingInstance + + + :returns: The fetched BrandVettingInstance + """ + payload, _, _ = self._fetch() + return BrandVettingInstance( + self._version, + payload, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=self._solution["brand_vetting_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BrandVettingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BrandVettingInstance( + self._version, + payload, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=self._solution["brand_vetting_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> BrandVettingInstance: + """ + Asynchronous coroutine to fetch the BrandVettingInstance + + + :returns: The fetched BrandVettingInstance + """ + payload, _, _ = await self._fetch_async() + return BrandVettingInstance( + self._version, + payload, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=self._solution["brand_vetting_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BrandVettingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BrandVettingInstance( + self._version, + payload, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=self._solution["brand_vetting_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + vetting_provider=vetting_provider, vetting_id=vetting_id + ) + return BrandVettingInstance( + self._version, payload, brand_sid=self._solution["brand_sid"] + ) + + def create_with_http_info( + self, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the BrandVettingInstance and return response metadata + + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + vetting_provider=vetting_provider, vetting_id=vetting_id + ) + instance = BrandVettingInstance( + self._version, payload, brand_sid=self._solution["brand_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + vetting_provider=vetting_provider, vetting_id=vetting_id + ) + return BrandVettingInstance( + self._version, payload, brand_sid=self._solution["brand_sid"] + ) + + async def create_with_http_info_async( + self, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the BrandVettingInstance and return response metadata + + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + vetting_provider=vetting_provider, vetting_id=vetting_id + ) + instance = BrandVettingInstance( + self._version, payload, brand_sid=self._solution["brand_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BrandVettingInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + vetting_provider=vetting_provider, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BrandVettingInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + vetting_provider=vetting_provider, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BrandVettingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + vetting_provider=vetting_provider, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BrandVettingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + vetting_provider=vetting_provider, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with BrandVettingPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BrandVettingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with BrandVettingPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BrandVettingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..ddcbff4af8 --- /dev/null +++ b/twilio/rest/messaging/v1/deactivations.py @@ -0,0 +1,278 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info( + self, date: Union[date, object] = values.unset + ) -> ApiResponse: + """ + Fetch the DeactivationsInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + date=date, + ) + + async def fetch_with_http_info_async( + self, date: Union[date, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeactivationsInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Date": serialize.iso8601_date(date), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = self._fetch(date=date) + return DeactivationsInstance( + self._version, + payload, + ) + + def fetch_with_http_info( + self, date: Union[date, object] = values.unset + ) -> ApiResponse: + """ + Fetch the DeactivationsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(date=date) + instance = DeactivationsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self, date: Union[date, object] = values.unset) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Date": serialize.iso8601_date(date), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(date=date) + return DeactivationsInstance( + self._version, + payload, + ) + + async def fetch_with_http_info_async( + self, date: Union[date, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeactivationsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(date=date) + instance = DeactivationsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..76fea05f18 --- /dev/null +++ b/twilio/rest/messaging/v1/domain_certs.py @@ -0,0 +1,533 @@ +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.api_response import ApiResponse +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info(self, tls_cert: str) -> ApiResponse: + """ + Update the DomainCertsInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + tls_cert=tls_cert, + ) + + async def update_with_http_info_async(self, tls_cert: str) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainCertsInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the DomainCertsInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DomainCertsInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DomainCertsInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DomainCertsInstance: + """ + Fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + payload, _, _ = self._fetch() + return DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainCertsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DomainCertsInstance: + """ + Asynchronous coroutine to fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + payload, _, _ = await self._fetch_async() + return DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainCertsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, tls_cert: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "TlsCert": tls_cert, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(tls_cert=tls_cert) + return DomainCertsInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + def update_with_http_info(self, tls_cert: str) -> ApiResponse: + """ + Update the DomainCertsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(tls_cert=tls_cert) + instance = DomainCertsInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, tls_cert: str) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "TlsCert": tls_cert, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(tls_cert=tls_cert) + return DomainCertsInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + async def update_with_http_info_async(self, tls_cert: str) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainCertsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(tls_cert=tls_cert) + instance = DomainCertsInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..1fa8341f21 --- /dev/null +++ b/twilio/rest/messaging/v1/domain_config.py @@ -0,0 +1,549 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainConfigInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainConfigInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the DomainConfigInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainConfigInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DomainConfigInstance: + """ + Fetch the DomainConfigInstance + + + :returns: The fetched DomainConfigInstance + """ + payload, _, _ = self._fetch() + return DomainConfigInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainConfigInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DomainConfigInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DomainConfigInstance: + """ + Asynchronous coroutine to fetch the DomainConfigInstance + + + :returns: The fetched DomainConfigInstance + """ + payload, _, _ = await self._fetch_async() + return DomainConfigInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainConfigInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DomainConfigInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) + return DomainConfigInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the DomainConfigInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) + instance = DomainConfigInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) + return DomainConfigInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainConfigInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) + instance = DomainConfigInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..b8291f2585 --- /dev/null +++ b/twilio/rest/messaging/v1/domain_config_messaging_service.py @@ -0,0 +1,290 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainConfigMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainConfigMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DomainConfigMessagingServiceInstance: + """ + Fetch the DomainConfigMessagingServiceInstance + + + :returns: The fetched DomainConfigMessagingServiceInstance + """ + payload, _, _ = self._fetch() + return DomainConfigMessagingServiceInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainConfigMessagingServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DomainConfigMessagingServiceInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DomainConfigMessagingServiceInstance: + """ + Asynchronous coroutine to fetch the DomainConfigMessagingServiceInstance + + + :returns: The fetched DomainConfigMessagingServiceInstance + """ + payload, _, _ = await self._fetch_async() + return DomainConfigMessagingServiceInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainConfigMessagingServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DomainConfigMessagingServiceInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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/domain_validate_dn.py b/twilio/rest/messaging/v1/domain_validate_dn.py new file mode 100644 index 0000000000..04bac787e0 --- /dev/null +++ b/twilio/rest/messaging/v1/domain_validate_dn.py @@ -0,0 +1,264 @@ +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.api_response import ApiResponse +from twilio.base.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 DomainValidateDnInstance(InstanceResource): + """ + :ivar domain_sid: The unique string that we created to identify the Domain resource. + :ivar is_valid: + :ivar reason: + :ivar url: + """ + + 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.is_valid: Optional[bool] = payload.get("is_valid") + self.reason: Optional[str] = payload.get("reason") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "domain_sid": domain_sid or self.domain_sid, + } + + self._context: Optional[DomainValidateDnContext] = None + + @property + def _proxy(self) -> "DomainValidateDnContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DomainValidateDnContext for this DomainValidateDnInstance + """ + if self._context is None: + self._context = DomainValidateDnContext( + self._version, + domain_sid=self._solution["domain_sid"], + ) + return self._context + + def fetch(self) -> "DomainValidateDnInstance": + """ + Fetch the DomainValidateDnInstance + + + :returns: The fetched DomainValidateDnInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DomainValidateDnInstance": + """ + Asynchronous coroutine to fetch the DomainValidateDnInstance + + + :returns: The fetched DomainValidateDnInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainValidateDnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainValidateDnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 DomainValidateDnContext(InstanceContext): + + def __init__(self, version: Version, domain_sid: str): + """ + Initialize the DomainValidateDnContext + + :param version: Version that contains the resource + :param domain_sid: Unique string used to identify the domain. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "domain_sid": domain_sid, + } + self._uri = "/LinkShortening/Domains/{domain_sid}/ValidateDns".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DomainValidateDnInstance: + """ + Fetch the DomainValidateDnInstance + + + :returns: The fetched DomainValidateDnInstance + """ + payload, _, _ = self._fetch() + return DomainValidateDnInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainValidateDnInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DomainValidateDnInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DomainValidateDnInstance: + """ + Asynchronous coroutine to fetch the DomainValidateDnInstance + + + :returns: The fetched DomainValidateDnInstance + """ + payload, _, _ = await self._fetch_async() + return DomainValidateDnInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainValidateDnInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DomainValidateDnInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 DomainValidateDnList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the DomainValidateDnList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, domain_sid: str) -> DomainValidateDnContext: + """ + Constructs a DomainValidateDnContext + + :param domain_sid: Unique string used to identify the domain. + """ + return DomainValidateDnContext(self._version, domain_sid=domain_sid) + + def __call__(self, domain_sid: str) -> DomainValidateDnContext: + """ + Constructs a DomainValidateDnContext + + :param domain_sid: Unique string used to identify the domain. + """ + return DomainValidateDnContext(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/external_campaign.py b/twilio/rest/messaging/v1/external_campaign.py new file mode 100644 index 0000000000..dd16e80319 --- /dev/null +++ b/twilio/rest/messaging/v1/external_campaign.py @@ -0,0 +1,224 @@ +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.api_response import ApiResponse + +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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + campaign_id=campaign_id, + messaging_service_sid=messaging_service_sid, + cnp_migration=cnp_migration, + ) + return ExternalCampaignInstance(self._version, payload) + + def create_with_http_info( + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ExternalCampaignInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + campaign_id=campaign_id, + messaging_service_sid=messaging_service_sid, + cnp_migration=cnp_migration, + ) + instance = ExternalCampaignInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + campaign_id=campaign_id, + messaging_service_sid=messaging_service_sid, + cnp_migration=cnp_migration, + ) + return ExternalCampaignInstance(self._version, payload) + + async def create_with_http_info_async( + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ExternalCampaignInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + campaign_id=campaign_id, + messaging_service_sid=messaging_service_sid, + cnp_migration=cnp_migration, + ) + instance = ExternalCampaignInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..9549b84828 --- /dev/null +++ b/twilio/rest/messaging/v1/linkshortening_messaging_service.py @@ -0,0 +1,396 @@ +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.api_response import ApiResponse +from twilio.base.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 create_with_http_info(self) -> ApiResponse: + """ + Create the LinkshorteningMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info() + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the LinkshorteningMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the LinkshorteningMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the LinkshorteningMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self) -> LinkshorteningMessagingServiceInstance: + """ + Create the LinkshorteningMessagingServiceInstance + + + :returns: The created LinkshorteningMessagingServiceInstance + """ + payload, _, _ = self._create() + return LinkshorteningMessagingServiceInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the LinkshorteningMessagingServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = LinkshorteningMessagingServiceInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self) -> LinkshorteningMessagingServiceInstance: + """ + Asynchronous coroutine to create the LinkshorteningMessagingServiceInstance + + + :returns: The created LinkshorteningMessagingServiceInstance + """ + payload, _, _ = await self._create_async() + return LinkshorteningMessagingServiceInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the LinkshorteningMessagingServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = LinkshorteningMessagingServiceInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the LinkshorteningMessagingServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the LinkshorteningMessagingServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the LinkshorteningMessagingServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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..1d88d07d0f --- /dev/null +++ b/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py @@ -0,0 +1,285 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the LinkshorteningMessagingServiceDomainAssociationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the LinkshorteningMessagingServiceDomainAssociationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> LinkshorteningMessagingServiceDomainAssociationInstance: + """ + Fetch the LinkshorteningMessagingServiceDomainAssociationInstance + + + :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + """ + payload, _, _ = self._fetch() + return LinkshorteningMessagingServiceDomainAssociationInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the LinkshorteningMessagingServiceDomainAssociationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = LinkshorteningMessagingServiceDomainAssociationInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async( + self, + ) -> LinkshorteningMessagingServiceDomainAssociationInstance: + """ + Asynchronous coroutine to fetch the LinkshorteningMessagingServiceDomainAssociationInstance + + + :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + """ + payload, _, _ = await self._fetch_async() + return LinkshorteningMessagingServiceDomainAssociationInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the LinkshorteningMessagingServiceDomainAssociationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = LinkshorteningMessagingServiceDomainAssociationInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..227e36af9c --- /dev/null +++ b/twilio/rest/messaging/v1/request_managed_cert.py @@ -0,0 +1,275 @@ +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.api_response import ApiResponse +from twilio.base.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 update_with_http_info(self) -> ApiResponse: + """ + Update the RequestManagedCertInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info() + + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the RequestManagedCertInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self) -> RequestManagedCertInstance: + """ + Update the RequestManagedCertInstance + + + :returns: The updated RequestManagedCertInstance + """ + payload, _, _ = self._update() + return RequestManagedCertInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + def update_with_http_info(self) -> ApiResponse: + """ + Update the RequestManagedCertInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update() + instance = RequestManagedCertInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async(self) -> RequestManagedCertInstance: + """ + Asynchronous coroutine to update the RequestManagedCertInstance + + + :returns: The updated RequestManagedCertInstance + """ + payload, _, _ = await self._update_async() + return RequestManagedCertInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the RequestManagedCertInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async() + instance = RequestManagedCertInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 c12e1c3444..d7da850830 100644 --- a/twilio/rest/messaging/v1/service/__init__.py +++ b/twilio/rest/messaging/v1/service/__init__.py @@ -1,628 +1,871 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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 `36,000`. Default value is `36,000`. + :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 - """ - super(ServiceList, self).__init__(version) + self._solution = { + "sid": sid or self.sid, + } - # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) + self._context: Optional[ServiceContext] = None - 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): + @property + def _proxy(self) -> "ServiceContext": """ - Create 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 + 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 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: ServiceContext for this 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.messaging.v1.service.ServiceInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the ServiceInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists ServiceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the ServiceInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.messaging.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 delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately + Deletes the ServiceInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with success boolean, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.delete_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return ServicePage(self._version, response, self._solution) - - def get_page(self, target_url): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the ServiceInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServicePage + :returns: ApiResponse with success boolean, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.delete_with_http_info_async() - return ServicePage(self._version, response, self._solution) - - def get(self, sid): + def fetch(self) -> "ServiceInstance": """ - Constructs a ServiceContext + Fetch the ServiceInstance - :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: The fetched ServiceInstance """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.fetch() - def __call__(self, sid): + async def fetch_async(self) -> "ServiceInstance": """ - Constructs a ServiceContext + Asynchronous coroutine to fetch the ServiceInstance - :param sid: The SID that identifies the resource to fetch - :returns: twilio.rest.messaging.v1.service.ServiceContext - :rtype: twilio.rest.messaging.v1.service.ServiceContext - """ - return ServiceContext(self._version, sid=sid, ) - - def __repr__(self): + :returns: The fetched ServiceInstance """ - Provide a friendly representation + return await self._proxy.fetch_async() - :returns: Machine friendly representation - :rtype: str + def fetch_with_http_info(self) -> ApiResponse: """ - return '' - + Fetch the ServiceInstance with HTTP info -class ServicePage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, response, solution): + :returns: ApiResponse with instance, status code, and headers """ - Initialize the ServicePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + return self._proxy.fetch_with_http_info() - :returns: twilio.rest.messaging.v1.service.ServicePage - :rtype: twilio.rest.messaging.v1.service.ServicePage + async def fetch_with_http_info_async(self) -> ApiResponse: """ - super(ServicePage, self).__init__(version, response) + Asynchronous coroutine to fetch the ServiceInstance with HTTP info - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of ServiceInstance + return await self._proxy.fetch_with_http_info_async() - :param dict payload: Payload response from the API - - :returns: twilio.rest.messaging.v1.service.ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServiceInstance + 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": """ - return ServiceInstance(self._version, payload, ) + Update the ServiceInstance - def __repr__(self): - """ - Provide a friendly representation + :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 `36,000`. Default value is `36,000`. + :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: Machine friendly representation - :rtype: str + :returns: The updated ServiceInstance """ - return '' - + 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, + ) -class ServiceContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + 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 `36,000`. Default value is `36,000`. + :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 __init__(self, version, sid): + :returns: The updated ServiceInstance """ - Initialize the ServiceContext + 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, + ) - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :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 `36,000`. Default value is `36,000`. + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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, + ) - :returns: twilio.rest.messaging.v1.service.ServiceContext - :rtype: twilio.rest.messaging.v1.service.ServiceContext - """ - super(ServiceContext, self).__init__(version) + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :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 `36,000`. Default value is `36,000`. + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) - # 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): + @property + def alpha_senders(self) -> AlphaSenderList: """ - Update 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 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): + Access the alpha_senders """ - Fetch the ServiceInstance + return self._proxy.alpha_senders - :returns: The fetched ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServiceInstance + @property + def channel_senders(self) -> ChannelSenderList: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - - def delete(self): + Access the channel_senders """ - Deletes the ServiceInstance + return self._proxy.channel_senders - :returns: True if delete succeeds, False otherwise - :rtype: bool + @property + def destination_alpha_senders(self) -> DestinationAlphaSenderList: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Access the destination_alpha_senders + """ + return self._proxy.destination_alpha_senders @property - def phone_numbers(self): + def phone_numbers(self) -> PhoneNumberList: """ Access the phone_numbers - - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberList - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberList """ - if self._phone_numbers is None: - self._phone_numbers = PhoneNumberList(self._version, service_sid=self._solution['sid'], ) - return self._phone_numbers + return self._proxy.phone_numbers @property - def short_codes(self): + def short_codes(self) -> ShortCodeList: """ Access the short_codes - - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodeList - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeList """ - if self._short_codes is None: - self._short_codes = ShortCodeList(self._version, service_sid=self._solution['sid'], ) - return self._short_codes + return self._proxy.short_codes @property - def alpha_senders(self): + def us_app_to_person(self) -> UsAppToPersonList: """ - Access the alpha_senders + Access the us_app_to_person + """ + return self._proxy.us_app_to_person - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderList - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderList + @property + def us_app_to_person_usecases(self) -> UsAppToPersonUsecaseList: """ - if self._alpha_senders is None: - self._alpha_senders = AlphaSenderList(self._version, service_sid=self._solution['sid'], ) - return self._alpha_senders + Access the us_app_to_person_usecases + """ + 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 """ - 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. """ +class ServiceContext(InstanceContext): - class ScanMessageContent(object): - INHERIT = "inherit" - ENABLE = "enable" - DISABLE = "disable" + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The SID of the Service resource to update. + """ + super().__init__(version) - 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'), + # Path Solution + self._solution = { + "sid": sid, } + self._uri = "/Services/{sid}".format(**self._solution) - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + 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 - @property - def _proxy(self): + def _delete(self) -> tuple: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Internal helper for delete operation - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServiceContext + Returns: + tuple: (success_boolean, status_code, headers) """ - if self._context is None: - self._context = ServiceContext(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'] + 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'] + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + def delete(self) -> bool: """ - return self._properties['friendly_name'] + Deletes the ServiceInstance - @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 + :returns: True if delete succeeds, False otherwise """ - return self._properties['date_updated'] + success, _, _ = self._delete() + return success - @property - def inbound_request_url(self): + def delete_with_http_info(self) -> ApiResponse: """ - :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 - """ - return self._properties['inbound_request_url'] + Deletes the ServiceInstance and return response metadata - @property - def inbound_method(self): - """ - :returns: The HTTP method we use to call inbound_request_url - :rtype: unicode - """ - return self._properties['inbound_method'] - @property - def fallback_url(self): - """ - :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 + :returns: ApiResponse with success boolean, status code, and headers """ - return self._properties['fallback_url'] + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - @property - def fallback_method(self): - """ - :returns: The HTTP method we use to call fallback_url - :rtype: unicode + async def _delete_async(self) -> tuple: """ - return self._properties['fallback_method'] + Internal async helper for delete operation - @property - def status_callback(self): - """ - :returns: The URL we call to pass status updates about message delivery - :rtype: unicode + Returns: + tuple: (success_boolean, status_code, headers) """ - return self._properties['status_callback'] - @property - def sticky_sender(self): - """ - :returns: Whether to enable Sticky Sender on the Service instance - :rtype: bool - """ - return self._properties['sticky_sender'] + headers = values.of({}) - @property - def mms_converter(self): - """ - :returns: Whether to enable the MMS Converter for messages sent through the Service instance - :rtype: bool - """ - return self._properties['mms_converter'] + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - @property - def smart_encoding(self): + async def delete_async(self) -> bool: """ - :returns: Whether to enable Encoding for messages sent through the Service instance - :rtype: bool - """ - return self._properties['smart_encoding'] + Asynchronous coroutine that deletes the ServiceInstance - @property - def scan_message_content(self): - """ - :returns: Reserved - :rtype: ServiceInstance.ScanMessageContent - """ - return self._properties['scan_message_content'] - @property - def fallback_to_long_code(self): - """ - :returns: Whether to enable Fallback to Long Code for messages sent through the Service instance - :rtype: bool + :returns: True if delete succeeds, False otherwise """ - return self._properties['fallback_to_long_code'] + success, _, _ = await self._delete_async() + return success - @property - def area_code_geomatch(self): + async def delete_with_http_info_async(self) -> ApiResponse: """ - :returns: Whether to enable Area Code Geomatch on the Service Instance - :rtype: bool - """ - return self._properties['area_code_geomatch'] + Asynchronous coroutine that deletes the ServiceInstance and return response metadata - @property - def synchronous_validation(self): + + :returns: ApiResponse with success boolean, status code, and headers """ - :returns: Reserved - :rtype: bool + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: """ - return self._properties['synchronous_validation'] + Internal helper for fetch operation - @property - def validity_period(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: How long, in seconds, messages sent from the Service are valid - :rtype: unicode + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: """ - return self._properties['validity_period'] + Fetch the ServiceInstance - @property - def url(self): + + :returns: The fetched ServiceInstance """ - :returns: The absolute URL of the Service resource - :rtype: unicode + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: """ - return self._properties['url'] + Fetch the ServiceInstance and return response metadata - @property - def links(self): + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The absolute URLs of related resources - :rtype: unicode + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: """ - return self._properties['links'] + Internal async helper for fetch operation - def update(self, friendly_name=values.unset, inbound_request_url=values.unset, - inbound_method=values.unset, fallback_url=values.unset, - fallback_method=values.unset, status_callback=values.unset, - sticky_sender=values.unset, mms_converter=values.unset, - smart_encoding=values.unset, scan_message_content=values.unset, - fallback_to_long_code=values.unset, area_code_geomatch=values.unset, - validity_period=values.unset, synchronous_validation=values.unset): + Returns: + tuple: (payload, status_code, headers) """ - Update 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 + headers = values.of({}) - :returns: The updated ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServiceInstance - """ - return self._proxy.update( + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "InboundRequestUrl": inbound_request_url, + "InboundMethod": inbound_method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StickySender": serialize.boolean_to_string(sticky_sender), + "MmsConverter": serialize.boolean_to_string(mms_converter), + "SmartEncoding": serialize.boolean_to_string(smart_encoding), + "ScanMessageContent": scan_message_content, + "FallbackToLongCode": serialize.boolean_to_string( + fallback_to_long_code + ), + "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), + "ValidityPeriod": validity_period, + "SynchronousValidation": serialize.boolean_to_string( + synchronous_validation + ), + "Usecase": usecase, + "UseInboundWebhookOnNumber": serialize.boolean_to_string( + use_inbound_webhook_on_number + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. + :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 + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :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 `36,000`. Default value is `36,000`. + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( friendly_name=friendly_name, inbound_request_url=inbound_request_url, inbound_method=inbound_method, @@ -637,62 +880,1097 @@ def update(self, friendly_name=values.unset, inbound_request_url=values.unset, 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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "InboundRequestUrl": inbound_request_url, + "InboundMethod": inbound_method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StickySender": serialize.boolean_to_string(sticky_sender), + "MmsConverter": serialize.boolean_to_string(mms_converter), + "SmartEncoding": serialize.boolean_to_string(smart_encoding), + "ScanMessageContent": scan_message_content, + "FallbackToLongCode": serialize.boolean_to_string( + fallback_to_long_code + ), + "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), + "ValidityPeriod": validity_period, + "SynchronousValidation": serialize.boolean_to_string( + synchronous_validation + ), + "Usecase": usecase, + "UseInboundWebhookOnNumber": serialize.boolean_to_string( + use_inbound_webhook_on_number + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers ) - def fetch(self): + 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 `36,000`. Default value is `36,000`. + :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 """ - Fetch the ServiceInstance + payload, _, _ = await self._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 ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :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 `36,000`. Default value is `36,000`. + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: The fetched ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServiceInstance + @property + def alpha_senders(self) -> AlphaSenderList: """ - return self._proxy.fetch() + Access the alpha_senders + """ + if self._alpha_senders is None: + self._alpha_senders = AlphaSenderList( + self._version, + self._solution["sid"], + ) + return self._alpha_senders - def delete(self): + @property + def channel_senders(self) -> ChannelSenderList: """ - Deletes the ServiceInstance + Access the channel_senders + """ + if self._channel_senders is None: + self._channel_senders = ChannelSenderList( + self._version, + self._solution["sid"], + ) + return self._channel_senders - :returns: True if delete succeeds, False otherwise - :rtype: bool + @property + def destination_alpha_senders(self) -> DestinationAlphaSenderList: """ - return self._proxy.delete() + Access the destination_alpha_senders + """ + if self._destination_alpha_senders is None: + self._destination_alpha_senders = DestinationAlphaSenderList( + self._version, + self._solution["sid"], + ) + return self._destination_alpha_senders @property - def phone_numbers(self): + def phone_numbers(self) -> PhoneNumberList: """ Access the phone_numbers - - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberList - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberList """ - return self._proxy.phone_numbers + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList( + self._version, + self._solution["sid"], + ) + return self._phone_numbers @property - def short_codes(self): + def short_codes(self) -> ShortCodeList: """ Access the short_codes + """ + if self._short_codes is None: + self._short_codes = ShortCodeList( + self._version, + self._solution["sid"], + ) + return self._short_codes - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodeList - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeList + @property + def us_app_to_person(self) -> UsAppToPersonList: """ - return self._proxy.short_codes + Access the us_app_to_person + """ + if self._us_app_to_person is None: + self._us_app_to_person = UsAppToPersonList( + self._version, + self._solution["sid"], + ) + return self._us_app_to_person @property - def alpha_senders(self): + def us_app_to_person_usecases(self) -> UsAppToPersonUsecaseList: """ - Access the alpha_senders + Access the us_app_to_person_usecases + """ + if self._us_app_to_person_usecases is None: + self._us_app_to_person_usecases = UsAppToPersonUsecaseList( + self._version, + self._solution["sid"], + ) + return self._us_app_to_person_usecases - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderList - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderList + def __repr__(self) -> str: """ - return self._proxy.alpha_senders + 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, + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. + :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 + """ + payload, _, _ = self._create( + 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 ServiceInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :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 `36,000`. Default value is `36,000`. + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + 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, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 `36,000`. Default value is `36,000`. + :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 + """ + payload, _, _ = await self._create_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 ServiceInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :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 `36,000`. Default value is `36,000`. + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_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, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The SID of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The SID of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 5477fc0657..2d91b12ebd 100644 --- a/twilio/rest/messaging/v1/service/alpha_sender.py +++ b/twilio/rest/messaging/v1/service/alpha_sender.py @@ -1,395 +1,891 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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") - def __init__(self, version, service_sid): + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[AlphaSenderContext] = None + + @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 + return self._proxy.delete() - :param unicode alpha_sender: The Alphanumeric Sender ID string + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AlphaSenderInstance - :returns: The created AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({'AlphaSender': alpha_sender, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AlphaSenderInstance with HTTP info - return AlphaSenderInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AlphaSenderInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "AlphaSenderInstance": + """ + Fetch the AlphaSenderInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched AlphaSenderInstance """ - Lists AlphaSenderInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return 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) -> "AlphaSenderInstance": + """ + Asynchronous coroutine to fetch the AlphaSenderInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance] + + :returns: The fetched AlphaSenderInstance """ - 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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of AlphaSenderInstance records from the API. - Request is executed immediately + Fetch the AlphaSenderInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AlphaSenderInstance with HTTP info - return AlphaSenderPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of AlphaSenderInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderPage + :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 AlphaSenderContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the AlphaSenderContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the resource from. + :param sid: The SID of the AlphaSender resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/AlphaSenders/{sid}".format( + **self._solution ) - return AlphaSenderPage(self._version, response, self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation - def get(self, sid): + Returns: + tuple: (success_boolean, status_code, headers) """ - Constructs a AlphaSenderContext - :param sid: The SID that identifies the resource to fetch + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext + def delete(self) -> bool: """ - return AlphaSenderContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Deletes the AlphaSenderInstance + - def __call__(self, sid): + :returns: True if delete succeeds, False otherwise """ - Constructs a AlphaSenderContext + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AlphaSenderInstance and return response metadata - :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: ApiResponse with success boolean, status code, and headers """ - return AlphaSenderContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __repr__(self): + async def _delete_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for delete operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (success_boolean, status_code, headers) """ - return '' + headers = values.of({}) -class AlphaSenderPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the AlphaSenderPage + Asynchronous coroutine that deletes the AlphaSenderInstance - :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.messaging.v1.service.alpha_sender.AlphaSenderPage - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderPage + :returns: True if delete succeeds, False otherwise """ - super(AlphaSenderPage, self).__init__(version, response) + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AlphaSenderInstance and return response metadata - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: ApiResponse with success boolean, status code, and headers """ - Build an instance of AlphaSenderInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance + Returns: + tuple: (payload, status_code, headers) """ - return AlphaSenderInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AlphaSenderInstance: """ - Provide a friendly representation + Fetch the AlphaSenderInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched AlphaSenderInstance """ - return '' + payload, _, _ = self._fetch() + return AlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AlphaSenderInstance and return response metadata -class AlphaSenderContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, service_sid, sid): + :returns: ApiResponse with instance, status code, and headers """ - Initialize the AlphaSenderContext + payload, status_code, headers = self._fetch() + instance = AlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :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 + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext + Returns: + tuple: (payload, status_code, headers) """ - super(AlphaSenderContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/AlphaSenders/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + async def fetch_async(self) -> AlphaSenderInstance: """ - Fetch the AlphaSenderInstance + Asynchronous coroutine to fetch the AlphaSenderInstance + :returns: The fetched AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - + payload, _, _ = await self._fetch_async() return AlphaSenderInstance( 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_with_http_info_async(self) -> ApiResponse: """ - Deletes the AlphaSenderInstance + Asynchronous coroutine to fetch the AlphaSenderInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = AlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 AlphaSenderInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class AlphaSenderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AlphaSenderInstance: + """ + Build an instance of AlphaSenderInstance + + :param payload: Payload response from the API + """ + + return AlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" - def __init__(self, version, payload, service_sid, sid=None): + +class AlphaSenderList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - Initialize the AlphaSenderInstance + Initialize the AlphaSenderList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the resources from. - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance """ - super(AlphaSenderInstance, self).__init__(version) + super().__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')), - 'alpha_sender': payload.get('alpha_sender'), - 'capabilities': payload.get('capabilities'), - 'url': payload.get('url'), + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/AlphaSenders".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create(self, alpha_sender: str) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: AlphaSenderContext for this AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, alpha_sender: str) -> AlphaSenderInstance: """ - if self._context is None: - self._context = AlphaSenderContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + Create the AlphaSenderInstance + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + + :returns: The created AlphaSenderInstance + """ + payload, _, _ = self._create(alpha_sender=alpha_sender) + return AlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info(self, alpha_sender: str) -> ApiResponse: + """ + Create the AlphaSenderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(alpha_sender=alpha_sender) + instance = AlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, alpha_sender: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, alpha_sender: str) -> AlphaSenderInstance: + """ + Asynchronously create the AlphaSenderInstance + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + + :returns: The created AlphaSenderInstance + """ + payload, _, _ = await self._create_async(alpha_sender=alpha_sender) + return AlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async(self, alpha_sender: str) -> ApiResponse: + """ + Asynchronously create the AlphaSenderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + alpha_sender=alpha_sender + ) + instance = AlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AlphaSenderInstance]: + """ + Streams AlphaSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AlphaSenderInstance]: + """ + Asynchronously streams AlphaSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AlphaSenderInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AlphaSenderInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AlphaSenderInstance]: + """ + Lists AlphaSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AlphaSenderInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode + 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['sid'] - @property - def account_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Lists AlphaSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['account_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def service_sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + Asynchronously lists AlphaSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['service_sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> AlphaSenderPage: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :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_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 AlphaSenderPage(self._version, response, solution=self._solution) + + async def 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 ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + 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['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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AlphaSenderPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The Alphanumeric Sender ID string - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AlphaSenderPage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AlphaSenderPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: An array of values that describe whether the number can receive calls or messages - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AlphaSenderPage, status code, and headers """ - return self._properties['capabilities'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def url(self): + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AlphaSenderPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> AlphaSenderPage: + """ + Retrieve a specific page of AlphaSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AlphaSenderInstance """ - :returns: The absolute URL of the AlphaSender resource - :rtype: unicode + response = self._version.domain.twilio.request("GET", target_url) + return AlphaSenderPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> AlphaSenderPage: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of AlphaSenderInstance """ - Fetch the AlphaSenderInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return AlphaSenderPage(self._version, response, solution=self._solution) - :returns: The fetched AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance + def get(self, sid: str) -> AlphaSenderContext: """ - return self._proxy.fetch() + Constructs a AlphaSenderContext - def delete(self): + :param sid: The SID of the AlphaSender resource to fetch. """ - Deletes the AlphaSenderInstance + return AlphaSenderContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def __call__(self, sid: str) -> AlphaSenderContext: """ - return self._proxy.delete() + Constructs a AlphaSenderContext + + :param sid: The SID of the AlphaSender resource to fetch. + """ + return AlphaSenderContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..37a8f4d9a5 --- /dev/null +++ b/twilio/rest/messaging/v1/service/channel_sender.py @@ -0,0 +1,907 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ChannelSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelSenderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelSenderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelSenderInstance: + """ + Fetch the ChannelSenderInstance + + + :returns: The fetched ChannelSenderInstance + """ + payload, _, _ = self._fetch() + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelSenderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ChannelSenderInstance: + """ + Asynchronous coroutine to fetch the ChannelSenderInstance + + + :returns: The fetched ChannelSenderInstance + """ + payload, _, _ = await self._fetch_async() + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelSenderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(sid=sid) + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def create_with_http_info(self, sid: str) -> ApiResponse: + """ + Create the ChannelSenderInstance and return response metadata + + :param sid: The SID of the Channel Sender being added to the Service. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(sid=sid) + instance = ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(sid=sid) + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def create_with_http_info_async(self, sid: str) -> ApiResponse: + """ + Asynchronously create the ChannelSenderInstance and return response metadata + + :param sid: The SID of the Channel Sender being added to the Service. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(sid=sid) + instance = ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChannelSenderInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChannelSenderInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChannelSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChannelSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelSenderPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChannelSenderPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelSenderPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChannelSenderPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..4b8194b368 --- /dev/null +++ b/twilio/rest/messaging/v1/service/destination_alpha_sender.py @@ -0,0 +1,969 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DestinationAlphaSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DestinationAlphaSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DestinationAlphaSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DestinationAlphaSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the DestinationAlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DestinationAlphaSenderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DestinationAlphaSenderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DestinationAlphaSenderInstance: + """ + Fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + payload, _, _ = self._fetch() + return DestinationAlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DestinationAlphaSenderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DestinationAlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DestinationAlphaSenderInstance: + """ + Asynchronous coroutine to fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + payload, _, _ = await self._fetch_async() + return DestinationAlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DestinationAlphaSenderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DestinationAlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + alpha_sender=alpha_sender, iso_country_code=iso_country_code + ) + return DestinationAlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, alpha_sender: str, iso_country_code: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the DestinationAlphaSenderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + alpha_sender=alpha_sender, iso_country_code=iso_country_code + ) + instance = DestinationAlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, alpha_sender: str, iso_country_code: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + alpha_sender=alpha_sender, iso_country_code=iso_country_code + ) + return DestinationAlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, alpha_sender: str, iso_country_code: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the DestinationAlphaSenderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + alpha_sender=alpha_sender, iso_country_code=iso_country_code + ) + instance = DestinationAlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DestinationAlphaSenderInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + iso_country_code=iso_country_code, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DestinationAlphaSenderInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + iso_country_code=iso_country_code, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DestinationAlphaSenderInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + iso_country_code=iso_country_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DestinationAlphaSenderInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + iso_country_code=iso_country_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution + ) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with DestinationAlphaSenderPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DestinationAlphaSenderPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with DestinationAlphaSenderPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DestinationAlphaSenderPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 9256f0e163..9992fd0102 100644 --- a/twilio/rest/messaging/v1/service/phone_number.py +++ b/twilio/rest/messaging/v1/service/phone_number.py @@ -1,404 +1,893 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 + return self._proxy.delete() - :param unicode phone_number_sid: The SID of the Phone Number being added to the Service + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance - :returns: The created PhoneNumberInstance - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({'PhoneNumberSid': phone_number_sid, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PhoneNumberInstance with HTTP info - return PhoneNumberInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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 self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched PhoneNumberInstance """ - Lists PhoneNumberInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return self._proxy.fetch() + + async def fetch_async(self) -> "PhoneNumberInstance": + """ + 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.messaging.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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of PhoneNumberInstance records from the API. - Request is executed immediately + Fetch the PhoneNumberInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info - return PhoneNumberPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of PhoneNumberInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of PhoneNumberInstance - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberPage + :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 PhoneNumberPage(self._version, response, self._solution) +class PhoneNumberContext(InstanceContext): - def get(self, sid): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Constructs a PhoneNumberContext + Initialize the PhoneNumberContext - :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 fetch the resource from. + :param sid: The SID of the PhoneNumber resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/PhoneNumbers/{sid}".format( + **self._solution + ) - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberContext + def _delete(self) -> tuple: """ - return PhoneNumberContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Internal helper for delete operation - def __call__(self, sid): + Returns: + tuple: (success_boolean, status_code, headers) """ - Constructs a PhoneNumberContext - :param sid: The SID that identifies the resource to fetch + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.messaging.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): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the PhoneNumberInstance and return response metadata -class PhoneNumberPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, response, solution): + async def _delete_async(self) -> tuple: """ - Initialize the PhoneNumberPage + Internal async helper for delete operation - :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: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberPage - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberPage + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(PhoneNumberPage, self).__init__(version, response) + Asynchronous coroutine that deletes the PhoneNumberInstance - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: True if delete succeeds, False otherwise """ - Build an instance of PhoneNumberInstance + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance and return response metadata - :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 + :returns: ApiResponse with success boolean, status code, and headers """ - return PhoneNumberInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __repr__(self): + def _fetch(self) -> tuple: """ - Provide a friendly representation + Internal helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class PhoneNumberContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> PhoneNumberInstance: """ - Initialize the PhoneNumberContext + Fetch the PhoneNumberInstance - :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 - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberContext + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = self._fetch() + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: """ - super(PhoneNumberContext, self).__init__(version) + Fetch the PhoneNumberInstance and return response metadata - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/PhoneNumbers/{sid}'.format(**self._solution) - def delete(self): + :returns: ApiResponse with instance, status code, and headers """ - Deletes the PhoneNumberInstance + payload, status_code, headers = self._fetch() + instance = PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def _fetch_async(self) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal async helper for fetch operation - def fetch(self): + Returns: + tuple: (payload, status_code, headers) """ - Fetch the PhoneNumberInstance - :returns: The fetched PhoneNumberInstance - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> PhoneNumberInstance: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronous coroutine to fetch the PhoneNumberInstance + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = await self._fetch_async() 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"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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. """ +class PhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: + """ + Build an instance of PhoneNumberInstance + + :param payload: Payload response from the API + """ + + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - def __init__(self, version, payload, service_sid, sid=None): + def __repr__(self) -> str: """ - Initialize the PhoneNumberInstance + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the resources from. - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance """ - super(PhoneNumberInstance, self).__init__(version) + super().__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'), - 'country_code': payload.get('country_code'), - 'capabilities': payload.get('capabilities'), - 'url': payload.get('url'), + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/PhoneNumbers".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create(self, phone_number_sid: str) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: PhoneNumberContext for this PhoneNumberInstance - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, phone_number_sid: str) -> PhoneNumberInstance: """ - if self._context is None: - self._context = PhoneNumberContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + Create the PhoneNumberInstance + + :param phone_number_sid: The SID of the Phone Number being added to the Service. + + :returns: The created PhoneNumberInstance + """ + payload, _, _ = self._create(phone_number_sid=phone_number_sid) + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info(self, phone_number_sid: str) -> ApiResponse: + """ + Create the PhoneNumberInstance and return response metadata + + :param phone_number_sid: The SID of the Phone Number being added to the Service. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(phone_number_sid=phone_number_sid) + instance = PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, phone_number_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: + """ + Asynchronously create the PhoneNumberInstance + + :param phone_number_sid: The SID of the Phone Number being added to the Service. + + :returns: The created PhoneNumberInstance + """ + payload, _, _ = await self._create_async(phone_number_sid=phone_number_sid) + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async(self, phone_number_sid: str) -> ApiResponse: + """ + Asynchronously create the PhoneNumberInstance and return response metadata + + :param phone_number_sid: The SID of the Phone Number being added to the Service. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number_sid=phone_number_sid + ) + instance = PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PhoneNumberInstance]: + """ + Streams PhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PhoneNumberInstance]: + """ + Asynchronously streams PhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PhoneNumberInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PhoneNumberInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: + """ + Lists PhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode + 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['sid'] - @property - def account_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Lists PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['account_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def service_sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + Asynchronously lists PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['service_sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> PhoneNumberPage: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + 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['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 PhoneNumberPage(self._version, response, solution=self._solution) + + async def 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 ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + 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['date_updated'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def phone_number(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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The phone number in E.164 format - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PhoneNumberPage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The 2-character ISO Country Code of the number - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PhoneNumberPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 bf17aa9df1..f1e7039dfc 100644 --- a/twilio/rest/messaging/v1/service/short_code.py +++ b/twilio/rest/messaging/v1/service/short_code.py @@ -1,404 +1,891 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 + return self._proxy.delete() - :param unicode short_code_sid: The SID of the ShortCode being added to the Service + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ShortCodeInstance - :returns: The created ShortCodeInstance - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({'ShortCodeSid': short_code_sid, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ShortCodeInstance with HTTP info - return ShortCodeInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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 self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ShortCodeInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.messaging.v1.service.short_code.ShortCodeInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "ShortCodeInstance": + """ + Fetch the ShortCodeInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched ShortCodeInstance """ - Lists ShortCodeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + 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) -> "ShortCodeInstance": + """ + Asynchronous coroutine to fetch the ShortCodeInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.messaging.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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of ShortCodeInstance records from the API. - Request is executed immediately + Fetch the ShortCodeInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ShortCodeInstance with HTTP info - return ShortCodePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of ShortCodeInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of ShortCodeInstance - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodePage + :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 ShortCodePage(self._version, response, self._solution) - def get(self, sid): +class ShortCodeContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): """ - Constructs a ShortCodeContext + Initialize the ShortCodeContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the resource from. + :param sid: The SID of the ShortCode resource to fetch. + """ + super().__init__(version) - :param sid: The SID that identifies the resource to fetch + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/ShortCodes/{sid}".format(**self._solution) - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodeContext - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeContext + def _delete(self) -> tuple: """ - return ShortCodeContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Internal helper for delete operation - def __call__(self, sid): + Returns: + tuple: (success_boolean, status_code, headers) """ - Constructs a ShortCodeContext - :param sid: The SID that identifies the resource to fetch + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodeContext - :rtype: twilio.rest.messaging.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): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the ShortCodeInstance and return response metadata -class ShortCodePage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, response, solution): + async def _delete_async(self) -> tuple: """ - Initialize the ShortCodePage + Internal async helper for delete operation - :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: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodePage - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodePage + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(ShortCodePage, self).__init__(version, response) + Asynchronous coroutine that deletes the ShortCodeInstance - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: True if delete succeeds, False otherwise """ - Build an instance of ShortCodeInstance + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ShortCodeInstance and return response metadata - :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 + :returns: ApiResponse with success boolean, status code, and headers """ - return ShortCodeInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __repr__(self): + def _fetch(self) -> tuple: """ - Provide a friendly representation + Internal helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class ShortCodeContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> ShortCodeInstance: """ - Initialize the ShortCodeContext + Fetch the ShortCodeInstance - :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 - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodeContext - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeContext + :returns: The fetched ShortCodeInstance + """ + payload, _, _ = self._fetch() + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: """ - super(ShortCodeContext, self).__init__(version) + Fetch the ShortCodeInstance and return response metadata - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/ShortCodes/{sid}'.format(**self._solution) - def delete(self): + :returns: ApiResponse with instance, status code, and headers """ - Deletes the ShortCodeInstance + payload, status_code, headers = self._fetch() + instance = ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def _fetch_async(self) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal async helper for fetch operation - def fetch(self): + Returns: + tuple: (payload, status_code, headers) """ - Fetch the ShortCodeInstance - :returns: The fetched ShortCodeInstance - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeInstance + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ShortCodeInstance: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronous coroutine to fetch the ShortCodeInstance + + :returns: The fetched ShortCodeInstance + """ + payload, _, _ = await self._fetch_async() 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"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ShortCodeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ShortCodeInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ShortCodePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ShortCodeInstance: + """ + Build an instance of ShortCodeInstance + + :param payload: Payload response from the API + """ + + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - def __init__(self, version, payload, service_sid, sid=None): + def __repr__(self) -> str: """ - Initialize the ShortCodeInstance + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ShortCodeList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ShortCodeList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the resources from. - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodeInstance - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeInstance """ - super(ShortCodeInstance, self).__init__(version) + super().__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'), - 'country_code': payload.get('country_code'), - 'capabilities': payload.get('capabilities'), - 'url': payload.get('url'), + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/ShortCodes".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create(self, short_code_sid: str) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: ShortCodeContext for this ShortCodeInstance - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, short_code_sid: str) -> ShortCodeInstance: """ - if self._context is None: - self._context = ShortCodeContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + Create the ShortCodeInstance + + :param short_code_sid: The SID of the ShortCode resource being added to the Service. + + :returns: The created ShortCodeInstance + """ + payload, _, _ = self._create(short_code_sid=short_code_sid) + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info(self, short_code_sid: str) -> ApiResponse: + """ + Create the ShortCodeInstance and return response metadata + + :param short_code_sid: The SID of the ShortCode resource being added to the Service. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(short_code_sid=short_code_sid) + instance = ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, short_code_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, short_code_sid: str) -> ShortCodeInstance: + """ + Asynchronously create the ShortCodeInstance + + :param short_code_sid: The SID of the ShortCode resource being added to the Service. + + :returns: The created ShortCodeInstance + """ + payload, _, _ = await self._create_async(short_code_sid=short_code_sid) + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async(self, short_code_sid: str) -> ApiResponse: + """ + Asynchronously create the ShortCodeInstance and return response metadata + + :param short_code_sid: The SID of the ShortCode resource being added to the Service. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + short_code_sid=short_code_sid + ) + instance = ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ShortCodeInstance]: + """ + Streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ShortCodeInstance]: + """ + Asynchronously streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ShortCodeInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ShortCodeInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: + """ + Lists ShortCodeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Asynchronously lists ShortCodeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['sid'] - @property - def account_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Lists ShortCodeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['account_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def service_sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + Asynchronously lists ShortCodeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['service_sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> ShortCodePage: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + 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['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 ShortCodePage(self._version, response, solution=self._solution) + + async def 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 ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + 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['date_updated'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def short_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 ShortCodePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The E.164 format of the short code - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ShortCodePage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ShortCodePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The 2-character ISO Country Code of the number - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ShortCodePage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ShortCodePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..ba3bfdc125 --- /dev/null +++ b/twilio/rest/messaging/v1/service/us_app_to_person.py @@ -0,0 +1,1849 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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. + :ivar privacy_policy_url: The URL of the privacy policy for the campaign. + :ivar terms_and_conditions_url: The URL of the terms and conditions for the campaign. + """ + + 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.privacy_policy_url: Optional[str] = payload.get("privacy_policy_url") + self.terms_and_conditions_url: Optional[str] = payload.get( + "terms_and_conditions_url" + ) + + 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UsAppToPersonInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UsAppToPersonInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> "UsAppToPersonInstance": + """ + Fetch the UsAppToPersonInstance + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: The fetched UsAppToPersonInstance + """ + return self._proxy.fetch( + x_twilio_api_version=x_twilio_api_version, + ) + + async def fetch_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> "UsAppToPersonInstance": + """ + Asynchronous coroutine to fetch the UsAppToPersonInstance + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: The fetched UsAppToPersonInstance + """ + return await self._proxy.fetch_async( + x_twilio_api_version=x_twilio_api_version, + ) + + def fetch_with_http_info( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the UsAppToPersonInstance with HTTP info + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + x_twilio_api_version=x_twilio_api_version, + ) + + async def fetch_with_http_info_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UsAppToPersonInstance with HTTP info + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + x_twilio_api_version=x_twilio_api_version, + ) + + 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, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> "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. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :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, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + + 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, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> "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. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :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, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + + def update_with_http_info( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UsAppToPersonInstance with HTTP info + + :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. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + + async def update_with_http_info_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, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UsAppToPersonInstance with HTTP info + + :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. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the UsAppToPersonInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UsAppToPersonInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UsAppToPersonInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self, x_twilio_api_version: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + x_twilio_api_version is values.unset + or (isinstance(x_twilio_api_version, str) and not x_twilio_api_version) + ): + headers["X-Twilio-Api-Version"] = x_twilio_api_version + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> UsAppToPersonInstance: + """ + Fetch the UsAppToPersonInstance + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: The fetched UsAppToPersonInstance + """ + payload, _, _ = self._fetch(x_twilio_api_version=x_twilio_api_version) + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the UsAppToPersonInstance and return response metadata + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + x_twilio_api_version=x_twilio_api_version + ) + instance = UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + x_twilio_api_version is values.unset + or (isinstance(x_twilio_api_version, str) and not x_twilio_api_version) + ): + headers["X-Twilio-Api-Version"] = x_twilio_api_version + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> UsAppToPersonInstance: + """ + Asynchronous coroutine to fetch the UsAppToPersonInstance + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: The fetched UsAppToPersonInstance + """ + payload, _, _ = await self._fetch_async( + x_twilio_api_version=x_twilio_api_version + ) + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UsAppToPersonInstance and return response metadata + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + x_twilio_api_version=x_twilio_api_version + ) + instance = UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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), + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + } + ) + headers = values.of({}) + + if not ( + x_twilio_api_version is values.unset + or (isinstance(x_twilio_api_version, str) and not x_twilio_api_version) + ): + headers["X-Twilio-Api-Version"] = x_twilio_api_version + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> 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. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: The updated UsAppToPersonInstance + """ + payload, _, _ = self._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, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UsAppToPersonInstance and return response metadata + + :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. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + instance = UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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), + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + } + ) + headers = values.of({}) + + if not ( + x_twilio_api_version is values.unset + or (isinstance(x_twilio_api_version, str) and not x_twilio_api_version) + ): + headers["X-Twilio-Api-Version"] = x_twilio_api_version + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> 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. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: The updated UsAppToPersonInstance + """ + payload, _, _ = await self._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, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UsAppToPersonInstance and return response metadata + + :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. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + instance = UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + x_twilio_api_version: Union[str, object] = values.unset, + 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, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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), + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + } + ) + headers = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + x_twilio_api_version: Union[str, object] = values.unset, + 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, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, 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 x_twilio_api_version: The version of the Messaging API to use for this request + :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. + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: The created UsAppToPersonInstance + """ + payload, _, _ = self._create( + brand_registration_sid=brand_registration_sid, + description=description, + message_flow=message_flow, + message_samples=message_samples, + us_app_to_person_usecase=us_app_to_person_usecase, + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + x_twilio_api_version=x_twilio_api_version, + opt_in_message=opt_in_message, + opt_out_message=opt_out_message, + help_message=help_message, + opt_in_keywords=opt_in_keywords, + opt_out_keywords=opt_out_keywords, + help_keywords=help_keywords, + subscriber_opt_in=subscriber_opt_in, + age_gated=age_gated, + direct_lending=direct_lending, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def create_with_http_info( + 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, + x_twilio_api_version: Union[str, object] = values.unset, + 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, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the UsAppToPersonInstance and return response metadata + + :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 x_twilio_api_version: The version of the Messaging API to use for this request + :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. + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + brand_registration_sid=brand_registration_sid, + description=description, + message_flow=message_flow, + message_samples=message_samples, + us_app_to_person_usecase=us_app_to_person_usecase, + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + x_twilio_api_version=x_twilio_api_version, + opt_in_message=opt_in_message, + opt_out_message=opt_out_message, + help_message=help_message, + opt_in_keywords=opt_in_keywords, + opt_out_keywords=opt_out_keywords, + help_keywords=help_keywords, + subscriber_opt_in=subscriber_opt_in, + age_gated=age_gated, + direct_lending=direct_lending, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + instance = UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + x_twilio_api_version: Union[str, object] = values.unset, + 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, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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), + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + } + ) + headers = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + x_twilio_api_version: Union[str, object] = values.unset, + 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, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, 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 x_twilio_api_version: The version of the Messaging API to use for this request + :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. + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: The created UsAppToPersonInstance + """ + payload, _, _ = await self._create_async( + brand_registration_sid=brand_registration_sid, + description=description, + message_flow=message_flow, + message_samples=message_samples, + us_app_to_person_usecase=us_app_to_person_usecase, + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + x_twilio_api_version=x_twilio_api_version, + opt_in_message=opt_in_message, + opt_out_message=opt_out_message, + help_message=help_message, + opt_in_keywords=opt_in_keywords, + opt_out_keywords=opt_out_keywords, + help_keywords=help_keywords, + subscriber_opt_in=subscriber_opt_in, + age_gated=age_gated, + direct_lending=direct_lending, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def create_with_http_info_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, + x_twilio_api_version: Union[str, object] = values.unset, + 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, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the UsAppToPersonInstance and return response metadata + + :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 x_twilio_api_version: The version of the Messaging API to use for this request + :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. + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + brand_registration_sid=brand_registration_sid, + description=description, + message_flow=message_flow, + message_samples=message_samples, + us_app_to_person_usecase=us_app_to_person_usecase, + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + x_twilio_api_version=x_twilio_api_version, + opt_in_message=opt_in_message, + opt_out_message=opt_out_message, + help_message=help_message, + opt_in_keywords=opt_in_keywords, + opt_out_keywords=opt_out_keywords, + help_keywords=help_keywords, + subscriber_opt_in=subscriber_opt_in, + age_gated=age_gated, + direct_lending=direct_lending, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + instance = UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + x_twilio_api_version: Union[str, object] = values.unset, + 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 str x_twilio_api_version: The version of the Messaging API to use for this request + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + x_twilio_api_version=x_twilio_api_version, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + x_twilio_api_version: Union[str, object] = values.unset, + 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 str x_twilio_api_version: The version of the Messaging API to use for this request + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + x_twilio_api_version=x_twilio_api_version, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + x_twilio_api_version: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UsAppToPersonInstance and returns headers from first page + + + :param str x_twilio_api_version: The version of the Messaging API to use for this request + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + x_twilio_api_version=x_twilio_api_version, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + x_twilio_api_version: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UsAppToPersonInstance and returns headers from first page + + + :param str x_twilio_api_version: The version of the Messaging API to use for this request + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + x_twilio_api_version=x_twilio_api_version, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + x_twilio_api_version: Union[str, object] = values.unset, + 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 str x_twilio_api_version: The version of the Messaging API to use for this request + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + x_twilio_api_version=x_twilio_api_version, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + x_twilio_api_version: Union[str, object] = values.unset, + 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 str x_twilio_api_version: The version of the Messaging API to use for this request + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + x_twilio_api_version=x_twilio_api_version, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + x_twilio_api_version: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UsAppToPersonInstance and returns headers from first page + + + :param str x_twilio_api_version: The version of the Messaging API to use for this request + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + x_twilio_api_version=x_twilio_api_version, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + x_twilio_api_version: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UsAppToPersonInstance and returns headers from first page + + + :param str x_twilio_api_version: The version of the Messaging API to use for this request + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + x_twilio_api_version=x_twilio_api_version, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + x_twilio_api_version: Union[str, object] = values.unset, + 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 x_twilio_api_version: The version of the Messaging API to use for this request + :param page_token: PageToken provided by the API + :param page_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( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "Content-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, solution=self._solution) + + async def page_async( + self, + x_twilio_api_version: Union[str, object] = values.unset, + 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 x_twilio_api_version: The version of the Messaging API to use for this request + :param page_token: PageToken provided by the API + :param page_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( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "Content-Type": "application/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, solution=self._solution) + + def page_with_http_info( + self, + x_twilio_api_version: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UsAppToPersonPage, status code, and headers + """ + data = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UsAppToPersonPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + x_twilio_api_version: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UsAppToPersonPage, status code, and headers + """ + data = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UsAppToPersonPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..76ab18b76c --- /dev/null +++ b/twilio/rest/messaging/v1/service/us_app_to_person_usecase.py @@ -0,0 +1,198 @@ +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.api_response import ApiResponse + +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 + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "BrandRegistrationSid": brand_registration_sid, + } + ) + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers, params=params + ) + + def fetch( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> UsAppToPersonUsecaseInstance: + """ + Fetch the UsAppToPersonUsecaseInstance + + :param brand_registration_sid: The unique string to identify the A2P brand. + :returns: The fetched UsAppToPersonUsecaseInstance + """ + payload, _, _ = self._fetch(brand_registration_sid=brand_registration_sid) + return UsAppToPersonUsecaseInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def fetch_with_http_info( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the UsAppToPersonUsecaseInstance and return response metadata + + :param brand_registration_sid: The unique string to identify the A2P brand. + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + brand_registration_sid=brand_registration_sid + ) + instance = UsAppToPersonUsecaseInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "BrandRegistrationSid": brand_registration_sid, + } + ) + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + 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 + """ + payload, _, _ = await self._fetch_async( + brand_registration_sid=brand_registration_sid + ) + return UsAppToPersonUsecaseInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def fetch_with_http_info_async( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously fetch the UsAppToPersonUsecaseInstance and return response metadata + + :param brand_registration_sid: The unique string to identify the A2P brand. + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + brand_registration_sid=brand_registration_sid + ) + instance = UsAppToPersonUsecaseInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..844e16054e --- /dev/null +++ b/twilio/rest/messaging/v1/tollfree_verification.py @@ -0,0 +1,3082 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 BusinessRegistrationAuthority(object): + EIN = "EIN" + CBN = "CBN" + CRN = "CRN" + PROVINCIAL_NUMBER = "PROVINCIAL_NUMBER" + VAT = "VAT" + ACN = "ACN" + ABN = "ABN" + BRN = "BRN" + SIREN = "SIREN" + SIRET = "SIRET" + NZBN = "NZBN" + UST_IDNR = "USt-IdNr" + CIF = "CIF" + NIF = "NIF" + CNPJ = "CNPJ" + UID = "UID" + NEQ = "NEQ" + OTHER = "OTHER" + + class BusinessType(object): + PRIVATE_PROFIT = "PRIVATE_PROFIT" + PUBLIC_PROFIT = "PUBLIC_PROFIT" + SOLE_PROPRIETOR = "SOLE_PROPRIETOR" + NON_PROFIT = "NON_PROFIT" + GOVERNMENT = "GOVERNMENT" + + 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" + + class VettingProvider(object): + CAMPAIGN_VERIFY = "CAMPAIGN_VERIFY" + + """ + :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 as 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 tollfree_phone_number: The E.164 formatted toll-free phone number associated with the 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 business_registration_number: A legally recognized business registration number + :ivar business_registration_authority: + :ivar business_registration_country: Country business is registered in + :ivar business_type: + :ivar business_registration_phone_number: The E.164 formatted number associated with the business. + :ivar doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :ivar opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :ivar help_message_sample: A sample help message provided to users. + :ivar privacy_policy_url: The URL to the privacy policy for the business or organization. + :ivar terms_and_conditions_url: The URL of the terms and conditions for the business or organization. + :ivar age_gated_content: Indicates if the content is age gated. + :ivar opt_in_keywords: List of keywords that users can send to opt in or out of messages. + :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. + :ivar vetting_id: + :ivar vetting_provider: + :ivar vetting_id_expiration: + """ + + 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["TollfreeVerificationInstance.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.tollfree_phone_number: Optional[str] = payload.get("tollfree_phone_number") + 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.business_registration_number: Optional[str] = payload.get( + "business_registration_number" + ) + self.business_registration_authority: Optional[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority" + ] = payload.get("business_registration_authority") + self.business_registration_country: Optional[str] = payload.get( + "business_registration_country" + ) + self.business_type: Optional["TollfreeVerificationInstance.BusinessType"] = ( + payload.get("business_type") + ) + self.business_registration_phone_number: Optional[str] = payload.get( + "business_registration_phone_number" + ) + self.doing_business_as: Optional[str] = payload.get("doing_business_as") + self.opt_in_confirmation_message: Optional[str] = payload.get( + "opt_in_confirmation_message" + ) + self.help_message_sample: Optional[str] = payload.get("help_message_sample") + self.privacy_policy_url: Optional[str] = payload.get("privacy_policy_url") + self.terms_and_conditions_url: Optional[str] = payload.get( + "terms_and_conditions_url" + ) + self.age_gated_content: Optional[bool] = payload.get("age_gated_content") + self.opt_in_keywords: Optional[List[str]] = payload.get("opt_in_keywords") + 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.vetting_id: Optional[str] = payload.get("vetting_id") + self.vetting_provider: Optional[ + "TollfreeVerificationInstance.VettingProvider" + ] = payload.get("vetting_provider") + self.vetting_id_expiration: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("vetting_id_expiration") + ) + + 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TollfreeVerificationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TollfreeVerificationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TollfreeVerificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TollfreeVerificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: 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 as 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'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :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, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: 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 as 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'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :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, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + + def update_with_http_info( + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the TollfreeVerificationInstance with HTTP info + + :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 as 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'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + + async def update_with_http_info_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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TollfreeVerificationInstance with HTTP info + + :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 as 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'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_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 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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the TollfreeVerificationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TollfreeVerificationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TollfreeVerificationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TollfreeVerificationInstance: + """ + Fetch the TollfreeVerificationInstance + + + :returns: The fetched TollfreeVerificationInstance + """ + payload, _, _ = self._fetch() + return TollfreeVerificationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TollfreeVerificationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TollfreeVerificationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TollfreeVerificationInstance: + """ + Asynchronous coroutine to fetch the TollfreeVerificationInstance + + + :returns: The fetched TollfreeVerificationInstance + """ + payload, _, _ = await self._fetch_async() + return TollfreeVerificationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TollfreeVerificationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TollfreeVerificationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "BusinessRegistrationNumber": business_registration_number, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessRegistrationCountry": business_registration_country, + "BusinessType": business_type, + "BusinessRegistrationPhoneNumber": business_registration_phone_number, + "DoingBusinessAs": doing_business_as, + "OptInConfirmationMessage": opt_in_confirmation_message, + "HelpMessageSample": help_message_sample, + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + "AgeGatedContent": serialize.boolean_to_string(age_gated_content), + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "VettingProvider": vetting_provider, + "VettingId": vetting_id, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: 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 as 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'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: The updated TollfreeVerificationInstance + """ + payload, _, _ = self._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, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + return TollfreeVerificationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def update_with_http_info( + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the TollfreeVerificationInstance and return response metadata + + :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 as 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'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + instance = TollfreeVerificationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "BusinessRegistrationNumber": business_registration_number, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessRegistrationCountry": business_registration_country, + "BusinessType": business_type, + "BusinessRegistrationPhoneNumber": business_registration_phone_number, + "DoingBusinessAs": doing_business_as, + "OptInConfirmationMessage": opt_in_confirmation_message, + "HelpMessageSample": help_message_sample, + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + "AgeGatedContent": serialize.boolean_to_string(age_gated_content), + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "VettingProvider": vetting_provider, + "VettingId": vetting_id, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: 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 as 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'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: The updated TollfreeVerificationInstance + """ + payload, _, _ = await self._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, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + return TollfreeVerificationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TollfreeVerificationInstance and return response metadata + + :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 as 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'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + instance = TollfreeVerificationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "BusinessRegistrationNumber": business_registration_number, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessRegistrationCountry": business_registration_country, + "BusinessType": business_type, + "BusinessRegistrationPhoneNumber": business_registration_phone_number, + "DoingBusinessAs": doing_business_as, + "OptInConfirmationMessage": opt_in_confirmation_message, + "HelpMessageSample": help_message_sample, + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + "AgeGatedContent": serialize.boolean_to_string(age_gated_content), + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_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 as 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. + :param business_registration_number: A legally recognized business registration number. Required for all business types except SOLE_PROPRIETOR. + :param business_registration_authority: + :param business_registration_country: The country where the business is registered. Required for all business types except SOLE_PROPRIETOR. + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: The created TollfreeVerificationInstance + """ + payload, _, _ = self._create( + 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, + tollfree_phone_number_sid=tollfree_phone_number_sid, + customer_profile_sid=customer_profile_sid, + 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, + external_reference_id=external_reference_id, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + return TollfreeVerificationInstance(self._version, payload) + + def create_with_http_info( + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the TollfreeVerificationInstance and return response metadata + + :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 as 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. + :param business_registration_number: A legally recognized business registration number. Required for all business types except SOLE_PROPRIETOR. + :param business_registration_authority: + :param business_registration_country: The country where the business is registered. Required for all business types except SOLE_PROPRIETOR. + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + 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, + tollfree_phone_number_sid=tollfree_phone_number_sid, + customer_profile_sid=customer_profile_sid, + 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, + external_reference_id=external_reference_id, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + instance = TollfreeVerificationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "BusinessRegistrationNumber": business_registration_number, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessRegistrationCountry": business_registration_country, + "BusinessType": business_type, + "BusinessRegistrationPhoneNumber": business_registration_phone_number, + "DoingBusinessAs": doing_business_as, + "OptInConfirmationMessage": opt_in_confirmation_message, + "HelpMessageSample": help_message_sample, + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + "AgeGatedContent": serialize.boolean_to_string(age_gated_content), + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_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 as 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. + :param business_registration_number: A legally recognized business registration number. Required for all business types except SOLE_PROPRIETOR. + :param business_registration_authority: + :param business_registration_country: The country where the business is registered. Required for all business types except SOLE_PROPRIETOR. + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: The created TollfreeVerificationInstance + """ + payload, _, _ = await self._create_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, + tollfree_phone_number_sid=tollfree_phone_number_sid, + customer_profile_sid=customer_profile_sid, + 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, + external_reference_id=external_reference_id, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + return TollfreeVerificationInstance(self._version, payload) + + async def create_with_http_info_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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TollfreeVerificationInstance and return response metadata + + :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 as 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. + :param business_registration_number: A legally recognized business registration number. Required for all business types except SOLE_PROPRIETOR. + :param business_registration_authority: + :param business_registration_country: The country where the business is registered. Required for all business types except SOLE_PROPRIETOR. + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_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, + tollfree_phone_number_sid=tollfree_phone_number_sid, + customer_profile_sid=customer_profile_sid, + 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, + external_reference_id=external_reference_id, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + instance = TollfreeVerificationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + trust_product_sid: Union[List[str], 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 List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.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, + trust_product_sid=trust_product_sid, + 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, + trust_product_sid: Union[List[str], 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 List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(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, + trust_product_sid=trust_product_sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + trust_product_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TollfreeVerificationInstance and returns headers from first page + + + :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 List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + trust_product_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TollfreeVerificationInstance and returns headers from first page + + + :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 List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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, + trust_product_sid: Union[List[str], 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 List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + 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, + trust_product_sid=trust_product_sid, + 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, + trust_product_sid: Union[List[str], 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 List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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, + trust_product_sid=trust_product_sid, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + trust_product_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TollfreeVerificationInstance and returns headers from first page + + + :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 List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + trust_product_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TollfreeVerificationInstance and returns headers from first page + + + :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 List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, + trust_product_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, + ) -> 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 trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param page_token: PageToken provided by the API + :param page_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), + "TrustProductSid": serialize.map(trust_product_sid, 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 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, + trust_product_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, + ) -> 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 trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param page_token: PageToken provided by the API + :param page_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), + "TrustProductSid": serialize.map(trust_product_sid, 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 TollfreeVerificationPage(self._version, response) + + def page_with_http_info( + 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, + trust_product_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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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 trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TollfreeVerificationPage, status code, and headers + """ + data = values.of( + { + "TollfreePhoneNumberSid": tollfree_phone_number_sid, + "Status": status, + "ExternalReferenceId": external_reference_id, + "IncludeSubAccounts": serialize.boolean_to_string(include_sub_accounts), + "TrustProductSid": serialize.map(trust_product_sid, 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TollfreeVerificationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + trust_product_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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 trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TollfreeVerificationPage, status code, and headers + """ + data = values.of( + { + "TollfreePhoneNumberSid": tollfree_phone_number_sid, + "Status": status, + "ExternalReferenceId": external_reference_id, + "IncludeSubAccounts": serialize.boolean_to_string(include_sub_accounts), + "TrustProductSid": serialize.map(trust_product_sid, 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TollfreeVerificationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..46e9bf390f --- /dev/null +++ b/twilio/rest/messaging/v1/usecase.py @@ -0,0 +1,135 @@ +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.api_response import ApiResponse + +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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UsecaseInstance: + """ + Fetch the UsecaseInstance + + + :returns: The fetched UsecaseInstance + """ + payload, _, _ = self._fetch() + return UsecaseInstance(self._version, payload) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UsecaseInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UsecaseInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> UsecaseInstance: + """ + Asynchronously fetch the UsecaseInstance + + + :returns: The fetched UsecaseInstance + """ + payload, _, _ = await self._fetch_async() + return UsecaseInstance(self._version, payload) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously fetch the UsecaseInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UsecaseInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..8dd64eba5c --- /dev/null +++ b/twilio/rest/messaging/v2/__init__.py @@ -0,0 +1,59 @@ +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 +from twilio.rest.messaging.v2.domain_certs import DomainCertsList +from twilio.rest.messaging.v2.typing_indicator import TypingIndicatorList + + +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 + self._domain_certs: Optional[DomainCertsList] = None + self._typing_indicator: Optional[TypingIndicatorList] = None + + @property + def channels_senders(self) -> ChannelsSenderList: + if self._channels_senders is None: + self._channels_senders = ChannelsSenderList(self) + return self._channels_senders + + @property + def domain_certs(self) -> DomainCertsList: + if self._domain_certs is None: + self._domain_certs = DomainCertsList(self) + return self._domain_certs + + @property + def typing_indicator(self) -> TypingIndicatorList: + if self._typing_indicator is None: + self._typing_indicator = TypingIndicatorList(self) + return self._typing_indicator + + 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..46d944f1ff --- /dev/null +++ b/twilio/rest/messaging/v2/channels_sender.py @@ -0,0 +1,1985 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 (WABA) to use for this sender. + :ivar verification_method: The verification method. + :ivar verification_code: The verification code. + :ivar voice_application_sid: The SID of the Twilio Voice application. + :ivar account_type: The account type for ISV Account Type Migration. Set to 'ISV' or 'ISVSubAccount' to configure, empty string to clear, or omit to preserve the existing value. + """ + + 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" + ) + self.account_type: Optional["ChannelsSenderInstance.str"] = payload.get( + "account_type" + ) + + 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, + "account_type": self.account_type, + } + + class MessagingV2ChannelsSenderProfile(object): + """ + :ivar name: The name of the sender. Required for WhatsApp senders and must follow [Meta's display name guidelines](https://www.facebook.com/business/help/757569725593362). + :ivar about: The profile about text for the sender. + :ivar address: The address of the sender. + :ivar description: The description of the sender. + :ivar logo_url: The logo URL of the sender. + :ivar banner_url: The banner URL of the sender. + :ivar privacy_url: The privacy URL of the sender. Must be a publicly accessible HTTP or HTTPS URI associated with the sender. + :ivar terms_of_service_url: The terms of service URL of the sender. + :ivar accent_color: The color theme of the sender. Must be in hex format and have at least a 4:5:1 contrast ratio against white. + :ivar use_case: The messaging use case type for the RCS sender. Allowed values are `PROMOTIONAL`, `TRANSACTIONAL`, `OTP`, `MULTI_USE`. Defaults to `MULTI_USE` if not provided. Cannot be modified after launch. + :ivar vertical: The vertical of the sender. Allowed values are: - `Alcohol` - `Automotive` - `Beauty, Spa and Salon` - `Clothing and Apparel` - `Education` - `Entertainment` - `Event Planning and Service` - `Finance and Banking` - `Food and Grocery` - `Hotel and Lodging` - `Matrimony Service` - `Medical and Health` - `Non-profit` - `Online Gambling` - `OTC Drugs` - `Other` - `Physical Gambling` - `Professional Services` - `Public Service` - `Restaurant` - `Shopping and Retail` - `Travel and Transportation` + :ivar websites: The websites of the sender. + :ivar emails: The emails of the sender. + :ivar phone_numbers: The phone numbers 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.logo_url: Optional[str] = payload.get("logo_url") + self.banner_url: Optional[str] = payload.get("banner_url") + self.privacy_url: Optional[str] = payload.get("privacy_url") + self.terms_of_service_url: Optional[str] = payload.get( + "terms_of_service_url" + ) + self.accent_color: Optional[str] = payload.get("accent_color") + self.use_case: Optional["ChannelsSenderInstance.str"] = payload.get( + "use_case" + ) + self.vertical: Optional[str] = payload.get("vertical") + self.websites: Optional[Dict[str, object]] = payload.get("websites") + self.emails: Optional[Dict[str, object]] = payload.get("emails") + self.phone_numbers: Optional[Dict[str, object]] = payload.get( + "phone_numbers" + ) + + def to_dict(self): + return { + "name": self.name, + "about": self.about, + "address": self.address, + "description": self.description, + "logo_url": self.logo_url, + "banner_url": self.banner_url, + "privacy_url": self.privacy_url, + "terms_of_service_url": self.terms_of_service_url, + "accent_color": self.accent_color, + "use_case": self.use_case, + "vertical": self.vertical, + "websites": self.websites, + "emails": self.emails, + "phone_numbers": self.phone_numbers, + } + + class MessagingV2ChannelsSenderProfileGenericResponseEmails(object): + """ + :ivar email: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.email: Optional[str] = payload.get("email") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "email": self.email, + "label": self.label, + } + + class MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers(object): + """ + :ivar phone_number: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_number: Optional[str] = payload.get("phone_number") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "phone_number": self.phone_number, + "label": self.label, + } + + class MessagingV2ChannelsSenderProfileGenericResponseWebsites(object): + """ + :ivar website: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.website: Optional[str] = payload.get("website") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "website": self.website, + "label": self.label, + } + + class MessagingV2ChannelsSenderRequestsCreate(object): + """ + :ivar sender_id: The ID of the sender in `whatsapp:` format. + :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 for the webhook. + :ivar fallback_url: The URL to send the fallback webhook to. + :ivar fallback_method: The HTTP method for the fallback webhook. + :ivar status_callback_url: The URL to send the status callback to. + :ivar status_callback_method: The HTTP method 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 MessagingV2RcsCarrier(object): + """ + :ivar name: The name of the carrier. For example, `Verizon` or `AT&T` for US. + :ivar status: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.status: Optional[MessagingV2RcsCarrierStatus] = payload.get("status") + + def to_dict(self): + return { + "name": self.name, + "status": self.status.to_dict() if self.status is not None else None, + } + + class MessagingV2RcsComplianceCountryResponse(object): + """ + :ivar country: The ISO 3166-1 alpha-2 country code. + :ivar registration_sid: The default compliance registration SID (e.g., from CR-Google) that applies to all countries unless overridden in the `countries` array. + :ivar status: + :ivar carriers: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.country: Optional[str] = payload.get("country") + self.registration_sid: Optional[str] = payload.get("registration_sid") + self.status: Optional[MessagingV2RcsCountryStatus] = payload.get("status") + self.carriers: Optional[List[MessagingV2RcsCarrier]] = payload.get( + "carriers" + ) + + def to_dict(self): + return { + "country": self.country, + "registration_sid": self.registration_sid, + "status": self.status.to_dict() if self.status is not None else None, + "carriers": ( + [carriers.to_dict() for carriers in self.carriers] + if self.carriers is not None + else None + ), + } + + class Status(object): + CREATING = "CREATING" + ONLINE = "ONLINE" + OFFLINE = "OFFLINE" + PENDING_VERIFICATION = "PENDING_VERIFICATION" + VERIFYING = "VERIFYING" + ONLINE_UPDATING = "ONLINE:UPDATING" + TWILIO_REVIEW = "TWILIO_REVIEW" + DRAFT = "DRAFT" + STUBBED = "STUBBED" + + class MessagingV2RcsCarrierStatus(object): + UNKNOWN = "UNKNOWN" + UNLAUNCHED = "UNLAUNCHED" + CARRIER_REVIEW = "CARRIER_REVIEW" + APPROVED = "APPROVED" + REJECTED = "REJECTED" + SUSPENDED = "SUSPENDED" + + class MessagingV2RcsCountryStatus(object): + ONLINE = "ONLINE" + OFFLINE = "OFFLINE" + TWILIO_REVIEW = "TWILIO_REVIEW" + PENDING_VERIFICATION = "PENDING_VERIFICATION" + + """ + :ivar sid: The SID of the sender. + :ivar status: + :ivar sender_id: The ID of the sender in `whatsapp:` format. + :ivar configuration: + :ivar webhook: + :ivar profile: + :ivar properties: + :ivar offline_reasons: The reasons why the sender is offline. + :ivar compliance: + :ivar url: The 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.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.compliance: Optional[str] = payload.get("compliance") + 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelsSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelsSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelsSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelsSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelsSenderInstance with HTTP info + + :param messaging_v2_channels_sender_requests_update: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update, + ) + + async def update_with_http_info_async( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelsSenderInstance with HTTP info + + :param messaging_v2_channels_sender_requests_update: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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 (WABA) to use for this sender. + :ivar verification_method: The verification method. + :ivar verification_code: The verification code. + :ivar voice_application_sid: The SID of the Twilio Voice application. + :ivar account_type: The account type for ISV Account Type Migration. Set to 'ISV' or 'ISVSubAccount' to configure, empty string to clear, or omit to preserve the existing value. + """ + + 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" + ) + self.account_type: Optional["ChannelsSenderInstance.str"] = payload.get( + "account_type" + ) + + 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, + "account_type": self.account_type, + } + + class MessagingV2ChannelsSenderProfile(object): + """ + :ivar name: The name of the sender. Required for WhatsApp senders and must follow [Meta's display name guidelines](https://www.facebook.com/business/help/757569725593362). + :ivar about: The profile about text for the sender. + :ivar address: The address of the sender. + :ivar description: The description of the sender. + :ivar logo_url: The logo URL of the sender. + :ivar banner_url: The banner URL of the sender. + :ivar privacy_url: The privacy URL of the sender. Must be a publicly accessible HTTP or HTTPS URI associated with the sender. + :ivar terms_of_service_url: The terms of service URL of the sender. + :ivar accent_color: The color theme of the sender. Must be in hex format and have at least a 4:5:1 contrast ratio against white. + :ivar use_case: The messaging use case type for the RCS sender. Allowed values are `PROMOTIONAL`, `TRANSACTIONAL`, `OTP`, `MULTI_USE`. Defaults to `MULTI_USE` if not provided. Cannot be modified after launch. + :ivar vertical: The vertical of the sender. Allowed values are: - `Alcohol` - `Automotive` - `Beauty, Spa and Salon` - `Clothing and Apparel` - `Education` - `Entertainment` - `Event Planning and Service` - `Finance and Banking` - `Food and Grocery` - `Hotel and Lodging` - `Matrimony Service` - `Medical and Health` - `Non-profit` - `Online Gambling` - `OTC Drugs` - `Other` - `Physical Gambling` - `Professional Services` - `Public Service` - `Restaurant` - `Shopping and Retail` - `Travel and Transportation` + :ivar websites: The websites of the sender. + :ivar emails: The emails of the sender. + :ivar phone_numbers: The phone numbers 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.logo_url: Optional[str] = payload.get("logo_url") + self.banner_url: Optional[str] = payload.get("banner_url") + self.privacy_url: Optional[str] = payload.get("privacy_url") + self.terms_of_service_url: Optional[str] = payload.get( + "terms_of_service_url" + ) + self.accent_color: Optional[str] = payload.get("accent_color") + self.use_case: Optional["ChannelsSenderInstance.str"] = payload.get( + "use_case" + ) + self.vertical: Optional[str] = payload.get("vertical") + self.websites: Optional[Dict[str, object]] = payload.get("websites") + self.emails: Optional[Dict[str, object]] = payload.get("emails") + self.phone_numbers: Optional[Dict[str, object]] = payload.get( + "phone_numbers" + ) + + def to_dict(self): + return { + "name": self.name, + "about": self.about, + "address": self.address, + "description": self.description, + "logo_url": self.logo_url, + "banner_url": self.banner_url, + "privacy_url": self.privacy_url, + "terms_of_service_url": self.terms_of_service_url, + "accent_color": self.accent_color, + "use_case": self.use_case, + "vertical": self.vertical, + "websites": self.websites, + "emails": self.emails, + "phone_numbers": self.phone_numbers, + } + + class MessagingV2ChannelsSenderProfileGenericResponseEmails(object): + """ + :ivar email: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.email: Optional[str] = payload.get("email") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "email": self.email, + "label": self.label, + } + + class MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers(object): + """ + :ivar phone_number: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_number: Optional[str] = payload.get("phone_number") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "phone_number": self.phone_number, + "label": self.label, + } + + class MessagingV2ChannelsSenderProfileGenericResponseWebsites(object): + """ + :ivar website: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.website: Optional[str] = payload.get("website") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "website": self.website, + "label": self.label, + } + + class MessagingV2ChannelsSenderRequestsCreate(object): + """ + :ivar sender_id: The ID of the sender in `whatsapp:` format. + :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 for the webhook. + :ivar fallback_url: The URL to send the fallback webhook to. + :ivar fallback_method: The HTTP method for the fallback webhook. + :ivar status_callback_url: The URL to send the status callback to. + :ivar status_callback_method: The HTTP method 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 MessagingV2RcsCarrier(object): + """ + :ivar name: The name of the carrier. For example, `Verizon` or `AT&T` for US. + :ivar status: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.status: Optional[MessagingV2RcsCarrierStatus] = payload.get("status") + + def to_dict(self): + return { + "name": self.name, + "status": self.status.to_dict() if self.status is not None else None, + } + + class MessagingV2RcsComplianceCountryResponse(object): + """ + :ivar country: The ISO 3166-1 alpha-2 country code. + :ivar registration_sid: The default compliance registration SID (e.g., from CR-Google) that applies to all countries unless overridden in the `countries` array. + :ivar status: + :ivar carriers: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.country: Optional[str] = payload.get("country") + self.registration_sid: Optional[str] = payload.get("registration_sid") + self.status: Optional[MessagingV2RcsCountryStatus] = payload.get("status") + self.carriers: Optional[List[MessagingV2RcsCarrier]] = payload.get( + "carriers" + ) + + def to_dict(self): + return { + "country": self.country, + "registration_sid": self.registration_sid, + "status": self.status.to_dict() if self.status is not None else None, + "carriers": ( + [carriers.to_dict() for carriers in self.carriers] + if self.carriers is not None + else None + ), + } + + def __init__(self, version: Version, sid: str): + """ + Initialize the ChannelsSenderContext + + :param version: Version that contains the resource + :param sid: The SID of the sender. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Channels/Senders/{sid}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ChannelsSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelsSenderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelsSenderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelsSenderInstance: + """ + Fetch the ChannelsSenderInstance + + + :returns: The fetched ChannelsSenderInstance + """ + payload, _, _ = self._fetch() + return ChannelsSenderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelsSenderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ChannelsSenderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ChannelsSenderInstance: + """ + Asynchronous coroutine to fetch the ChannelsSenderInstance + + + :returns: The fetched ChannelsSenderInstance + """ + payload, _, _ = await self._fetch_async() + return ChannelsSenderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelsSenderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ChannelsSenderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = messaging_v2_channels_sender_requests_update.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update + ) + return ChannelsSenderInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelsSenderInstance and return response metadata + + :param messaging_v2_channels_sender_requests_update: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update + ) + instance = ChannelsSenderInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = messaging_v2_channels_sender_requests_update.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update + ) + return ChannelsSenderInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelsSenderInstance and return response metadata + + :param messaging_v2_channels_sender_requests_update: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update + ) + instance = ChannelsSenderInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 (WABA) to use for this sender. + :ivar verification_method: The verification method. + :ivar verification_code: The verification code. + :ivar voice_application_sid: The SID of the Twilio Voice application. + :ivar account_type: The account type for ISV Account Type Migration. Set to 'ISV' or 'ISVSubAccount' to configure, empty string to clear, or omit to preserve the existing value. + """ + + 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" + ) + self.account_type: Optional["ChannelsSenderInstance.str"] = payload.get( + "account_type" + ) + + 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, + "account_type": self.account_type, + } + + class MessagingV2ChannelsSenderProfile(object): + """ + :ivar name: The name of the sender. Required for WhatsApp senders and must follow [Meta's display name guidelines](https://www.facebook.com/business/help/757569725593362). + :ivar about: The profile about text for the sender. + :ivar address: The address of the sender. + :ivar description: The description of the sender. + :ivar logo_url: The logo URL of the sender. + :ivar banner_url: The banner URL of the sender. + :ivar privacy_url: The privacy URL of the sender. Must be a publicly accessible HTTP or HTTPS URI associated with the sender. + :ivar terms_of_service_url: The terms of service URL of the sender. + :ivar accent_color: The color theme of the sender. Must be in hex format and have at least a 4:5:1 contrast ratio against white. + :ivar use_case: The messaging use case type for the RCS sender. Allowed values are `PROMOTIONAL`, `TRANSACTIONAL`, `OTP`, `MULTI_USE`. Defaults to `MULTI_USE` if not provided. Cannot be modified after launch. + :ivar vertical: The vertical of the sender. Allowed values are: - `Alcohol` - `Automotive` - `Beauty, Spa and Salon` - `Clothing and Apparel` - `Education` - `Entertainment` - `Event Planning and Service` - `Finance and Banking` - `Food and Grocery` - `Hotel and Lodging` - `Matrimony Service` - `Medical and Health` - `Non-profit` - `Online Gambling` - `OTC Drugs` - `Other` - `Physical Gambling` - `Professional Services` - `Public Service` - `Restaurant` - `Shopping and Retail` - `Travel and Transportation` + :ivar websites: The websites of the sender. + :ivar emails: The emails of the sender. + :ivar phone_numbers: The phone numbers 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.logo_url: Optional[str] = payload.get("logo_url") + self.banner_url: Optional[str] = payload.get("banner_url") + self.privacy_url: Optional[str] = payload.get("privacy_url") + self.terms_of_service_url: Optional[str] = payload.get( + "terms_of_service_url" + ) + self.accent_color: Optional[str] = payload.get("accent_color") + self.use_case: Optional["ChannelsSenderInstance.str"] = payload.get( + "use_case" + ) + self.vertical: Optional[str] = payload.get("vertical") + self.websites: Optional[Dict[str, object]] = payload.get("websites") + self.emails: Optional[Dict[str, object]] = payload.get("emails") + self.phone_numbers: Optional[Dict[str, object]] = payload.get( + "phone_numbers" + ) + + def to_dict(self): + return { + "name": self.name, + "about": self.about, + "address": self.address, + "description": self.description, + "logo_url": self.logo_url, + "banner_url": self.banner_url, + "privacy_url": self.privacy_url, + "terms_of_service_url": self.terms_of_service_url, + "accent_color": self.accent_color, + "use_case": self.use_case, + "vertical": self.vertical, + "websites": self.websites, + "emails": self.emails, + "phone_numbers": self.phone_numbers, + } + + class MessagingV2ChannelsSenderProfileGenericResponseEmails(object): + """ + :ivar email: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.email: Optional[str] = payload.get("email") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "email": self.email, + "label": self.label, + } + + class MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers(object): + """ + :ivar phone_number: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_number: Optional[str] = payload.get("phone_number") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "phone_number": self.phone_number, + "label": self.label, + } + + class MessagingV2ChannelsSenderProfileGenericResponseWebsites(object): + """ + :ivar website: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.website: Optional[str] = payload.get("website") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "website": self.website, + "label": self.label, + } + + class MessagingV2ChannelsSenderRequestsCreate(object): + """ + :ivar sender_id: The ID of the sender in `whatsapp:` format. + :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 for the webhook. + :ivar fallback_url: The URL to send the fallback webhook to. + :ivar fallback_method: The HTTP method for the fallback webhook. + :ivar status_callback_url: The URL to send the status callback to. + :ivar status_callback_method: The HTTP method 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 MessagingV2RcsCarrier(object): + """ + :ivar name: The name of the carrier. For example, `Verizon` or `AT&T` for US. + :ivar status: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.status: Optional[MessagingV2RcsCarrierStatus] = payload.get("status") + + def to_dict(self): + return { + "name": self.name, + "status": self.status.to_dict() if self.status is not None else None, + } + + class MessagingV2RcsComplianceCountryResponse(object): + """ + :ivar country: The ISO 3166-1 alpha-2 country code. + :ivar registration_sid: The default compliance registration SID (e.g., from CR-Google) that applies to all countries unless overridden in the `countries` array. + :ivar status: + :ivar carriers: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.country: Optional[str] = payload.get("country") + self.registration_sid: Optional[str] = payload.get("registration_sid") + self.status: Optional[MessagingV2RcsCountryStatus] = payload.get("status") + self.carriers: Optional[List[MessagingV2RcsCarrier]] = payload.get( + "carriers" + ) + + def to_dict(self): + return { + "country": self.country, + "registration_sid": self.registration_sid, + "status": self.status.to_dict() if self.status is not None else None, + "carriers": ( + [carriers.to_dict() for carriers in self.carriers] + if self.carriers is not None + else None + ), + } + + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + messaging_v2_channels_sender_requests_create=messaging_v2_channels_sender_requests_create + ) + return ChannelsSenderInstance(self._version, payload) + + def create_with_http_info( + self, + messaging_v2_channels_sender_requests_create: MessagingV2ChannelsSenderRequestsCreate, + ) -> ApiResponse: + """ + Create the ChannelsSenderInstance and return response metadata + + :param messaging_v2_channels_sender_requests_create: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + messaging_v2_channels_sender_requests_create=messaging_v2_channels_sender_requests_create + ) + instance = ChannelsSenderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + messaging_v2_channels_sender_requests_create: MessagingV2ChannelsSenderRequestsCreate, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + messaging_v2_channels_sender_requests_create=messaging_v2_channels_sender_requests_create + ) + return ChannelsSenderInstance(self._version, payload) + + async def create_with_http_info_async( + self, + messaging_v2_channels_sender_requests_create: MessagingV2ChannelsSenderRequestsCreate, + ) -> ApiResponse: + """ + Asynchronously create the ChannelsSenderInstance and return response metadata + + :param messaging_v2_channels_sender_requests_create: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + messaging_v2_channels_sender_requests_create=messaging_v2_channels_sender_requests_create + ) + instance = ChannelsSenderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChannelsSenderInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + channel=channel, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChannelsSenderInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + channel=channel, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChannelsSenderInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + channel=channel, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChannelsSenderInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + channel=channel, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ChannelsSenderPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChannelsSenderPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ChannelsSenderPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChannelsSenderPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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: The SID of the sender. + """ + return ChannelsSenderContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ChannelsSenderContext: + """ + Constructs a ChannelsSenderContext + + :param sid: The SID of the 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/messaging/v2/domain_certs.py b/twilio/rest/messaging/v2/domain_certs.py new file mode 100644 index 0000000000..84c0f5b58c --- /dev/null +++ b/twilio/rest/messaging/v2/domain_certs.py @@ -0,0 +1,285 @@ +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.api_response import ApiResponse +from twilio.base.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 managed: Boolean field that indicates whether the certificate is managed by Twilio or uploaded by the customer. + :ivar requesting: Boolean field that indicates whether a Twilio managed cert request is in progress or completed. True indicates a request is in progress and false indicates the request has completed or not requested yet. + :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.managed: Optional[bool] = payload.get("managed") + self.requesting: Optional[bool] = payload.get("requesting") + 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 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 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 _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DomainCertsInstance: + """ + Fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + payload, _, _ = self._fetch() + return DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainCertsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DomainCertsInstance: + """ + Asynchronous coroutine to fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + payload, _, _ = await self._fetch_async() + return DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainCertsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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/v2/typing_indicator.py b/twilio/rest/messaging/v2/typing_indicator.py new file mode 100644 index 0000000000..e27ebdfb2c --- /dev/null +++ b/twilio/rest/messaging/v2/typing_indicator.py @@ -0,0 +1,169 @@ +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.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TypingIndicatorInstance(InstanceResource): + """ + :ivar success: Indicates if the typing indicator was sent successfully. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.success: Optional[bool] = payload.get("success") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class TypingIndicatorList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TypingIndicatorList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Indicators/Typing.json" + + def _create(self, channel: str, message_id: str) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "channel": channel, + "messageId": message_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, channel: str, message_id: str) -> TypingIndicatorInstance: + """ + Create the TypingIndicatorInstance + + :param channel: Shared channel identifier + :param message_id: Message SID that identifies the conversation thread for the typing indicator. Must be a valid Twilio Message SID (SM*) or Media SID (MM*) from an existing WhatsApp conversation. + + :returns: The created TypingIndicatorInstance + """ + payload, _, _ = self._create(channel=channel, message_id=message_id) + return TypingIndicatorInstance(self._version, payload) + + def create_with_http_info(self, channel: str, message_id: str) -> ApiResponse: + """ + Create the TypingIndicatorInstance and return response metadata + + :param channel: Shared channel identifier + :param message_id: Message SID that identifies the conversation thread for the typing indicator. Must be a valid Twilio Message SID (SM*) or Media SID (MM*) from an existing WhatsApp conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + channel=channel, message_id=message_id + ) + instance = TypingIndicatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, channel: str, message_id: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "channel": channel, + "messageId": message_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, channel: str, message_id: str + ) -> TypingIndicatorInstance: + """ + Asynchronously create the TypingIndicatorInstance + + :param channel: Shared channel identifier + :param message_id: Message SID that identifies the conversation thread for the typing indicator. Must be a valid Twilio Message SID (SM*) or Media SID (MM*) from an existing WhatsApp conversation. + + :returns: The created TypingIndicatorInstance + """ + payload, _, _ = await self._create_async(channel=channel, message_id=message_id) + return TypingIndicatorInstance(self._version, payload) + + async def create_with_http_info_async( + self, channel: str, message_id: str + ) -> ApiResponse: + """ + Asynchronously create the TypingIndicatorInstance and return response metadata + + :param channel: Shared channel identifier + :param message_id: Message SID that identifies the conversation thread for the typing indicator. Must be a valid Twilio Message SID (SM*) or Media SID (MM*) from an existing WhatsApp conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + channel=channel, message_id=message_id + ) + instance = TypingIndicatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/messaging/v3/__init__.py b/twilio/rest/messaging/v3/__init__.py new file mode 100644 index 0000000000..20229f1936 --- /dev/null +++ b/twilio/rest/messaging/v3/__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.v3.typing_indicator import TypingIndicatorList + + +class V3(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V3 version of Messaging + + :param domain: The Twilio.messaging domain + """ + super().__init__(domain, "v3") + self._typing_indicator: Optional[TypingIndicatorList] = None + + @property + def typing_indicator(self) -> TypingIndicatorList: + if self._typing_indicator is None: + self._typing_indicator = TypingIndicatorList(self) + return self._typing_indicator + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/messaging/v3/typing_indicator.py b/twilio/rest/messaging/v3/typing_indicator.py new file mode 100644 index 0000000000..2fc385b528 --- /dev/null +++ b/twilio/rest/messaging/v3/typing_indicator.py @@ -0,0 +1,220 @@ +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.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TypingIndicatorInstance(InstanceResource): + + class TypingIndicatorRequest(object): + """ + :ivar channel: The messaging channel. Must be \"APPLE\". + :ivar message_id: The SID of a recent inbound message from the recipient. Must be an SM or MM SID format. + :ivar _from: The Apple Messages for Business identifier of the sender (business). + :ivar to: The Apple Messages for Business identifier of the recipient (customer). + :ivar event: The type of typing event. \"START\" indicates the agent began typing, \"END\" indicates the agent stopped typing. Defaults to \"START\". + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channel: Optional["TypingIndicatorInstance.str"] = payload.get( + "channel" + ) + self.message_id: Optional[str] = payload.get("messageId") + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.event: Optional["TypingIndicatorInstance.str"] = payload.get("event") + + def to_dict(self): + return { + "channel": self.channel, + "messageId": self.message_id, + "from": self._from, + "to": self.to, + "event": self.event, + } + + """ + :ivar success: Indicates if the typing indicator was sent successfully. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.success: Optional[bool] = payload.get("success") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class TypingIndicatorList(ListResource): + + class TypingIndicatorRequest(object): + """ + :ivar channel: The messaging channel. Must be \"APPLE\". + :ivar message_id: The SID of a recent inbound message from the recipient. Must be an SM or MM SID format. + :ivar _from: The Apple Messages for Business identifier of the sender (business). + :ivar to: The Apple Messages for Business identifier of the recipient (customer). + :ivar event: The type of typing event. \"START\" indicates the agent began typing, \"END\" indicates the agent stopped typing. Defaults to \"START\". + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channel: Optional["TypingIndicatorInstance.str"] = payload.get( + "channel" + ) + self.message_id: Optional[str] = payload.get("messageId") + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.event: Optional["TypingIndicatorInstance.str"] = payload.get("event") + + def to_dict(self): + return { + "channel": self.channel, + "messageId": self.message_id, + "from": self._from, + "to": self.to, + "event": self.event, + } + + def __init__(self, version: Version): + """ + Initialize the TypingIndicatorList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Indicators/Typing.json" + + def _create(self, typing_indicator_request: TypingIndicatorRequest) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = typing_indicator_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, typing_indicator_request: TypingIndicatorRequest + ) -> TypingIndicatorInstance: + """ + Create the TypingIndicatorInstance + + :param typing_indicator_request: + + :returns: The created TypingIndicatorInstance + """ + payload, _, _ = self._create(typing_indicator_request=typing_indicator_request) + return TypingIndicatorInstance(self._version, payload) + + def create_with_http_info( + self, typing_indicator_request: TypingIndicatorRequest + ) -> ApiResponse: + """ + Create the TypingIndicatorInstance and return response metadata + + :param typing_indicator_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + typing_indicator_request=typing_indicator_request + ) + instance = TypingIndicatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, typing_indicator_request: TypingIndicatorRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = typing_indicator_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, typing_indicator_request: TypingIndicatorRequest + ) -> TypingIndicatorInstance: + """ + Asynchronously create the TypingIndicatorInstance + + :param typing_indicator_request: + + :returns: The created TypingIndicatorInstance + """ + payload, _, _ = await self._create_async( + typing_indicator_request=typing_indicator_request + ) + return TypingIndicatorInstance(self._version, payload) + + async def create_with_http_info_async( + self, typing_indicator_request: TypingIndicatorRequest + ) -> ApiResponse: + """ + Asynchronously create the TypingIndicatorInstance and return response metadata + + :param typing_indicator_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + typing_indicator_request=typing_indicator_request + ) + instance = TypingIndicatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 7ff0f27b03..f7666a0e3b 100644 --- a/twilio/rest/monitor/v1/alert.py +++ b/twilio/rest/monitor/v1/alert.py @@ -1,476 +1,798 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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, + } - def __init__(self, version): + self._context: Optional[AlertContext] = None + + @property + def _proxy(self) -> "AlertContext": """ - Initialize the AlertList + 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: AlertContext for this AlertInstance + """ + if self._context is None: + self._context = AlertContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.monitor.v1.alert.AlertList - :rtype: twilio.rest.monitor.v1.alert.AlertList + def fetch(self) -> "AlertInstance": """ - super(AlertList, self).__init__(version) + Fetch the AlertInstance - # Path Solution - self._solution = {} - self._uri = '/Alerts'.format(**self._solution) - def stream(self, log_level=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): + :returns: The fetched AlertInstance """ - Streams AlertInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param unicode log_level: Only show alerts for this log-level - :param date start_date: Only include alerts that occurred on or after this date and time - :param date 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) + return self._proxy.fetch() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.monitor.v1.alert.AlertInstance] + async def fetch_async(self) -> "AlertInstance": """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine to fetch the AlertInstance - page = self.page( - log_level=log_level, - start_date=start_date, - end_date=end_date, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched AlertInstance + """ + return await self._proxy.fetch_async() - def list(self, log_level=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): + def fetch_with_http_info(self) -> ApiResponse: """ - Lists AlertInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Fetch the AlertInstance with HTTP info - :param unicode log_level: Only show alerts for this log-level - :param date start_date: Only include alerts that occurred on or after this date and time - :param date 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] + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream( - log_level=log_level, - start_date=start_date, - end_date=end_date, - limit=limit, - page_size=page_size, - )) + return self._proxy.fetch_with_http_info() - 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of AlertInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the AlertInstance with HTTP info - :param unicode log_level: Only show alerts for this log-level - :param date start_date: Only include alerts that occurred on or after this date and time - :param date 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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'LogLevel': log_level, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return await self._proxy.fetch_with_http_info_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) - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return AlertPage(self._version, response, self._solution) +class AlertContext(InstanceContext): - def get_page(self, target_url): + def __init__(self, version: Version, sid: str): """ - Retrieve a specific page of AlertInstance records from the API. - Request is executed immediately + Initialize the AlertContext - :param str target_url: API-generated URL for the requested results page + :param version: Version that contains the resource + :param sid: The SID of the Alert resource to fetch. + """ + super().__init__(version) - :returns: Page of AlertInstance - :rtype: twilio.rest.monitor.v1.alert.AlertPage + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Alerts/{sid}".format(**self._solution) + + def _fetch(self) -> tuple: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) - return AlertPage(self._version, response, self._solution) + headers["Accept"] = "application/json" - def get(self, sid): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AlertInstance: """ - Constructs a AlertContext + 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, ) + payload, _, _ = self._fetch() + return AlertInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a AlertContext + Fetch the AlertInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return AlertContext(self._version, sid=sid, ) + payload, status_code, headers = self._fetch() + instance = AlertInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class AlertPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AlertInstance: """ - Initialize the AlertPage + Asynchronous coroutine to fetch the AlertInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.monitor.v1.alert.AlertPage - :rtype: twilio.rest.monitor.v1.alert.AlertPage + :returns: The fetched AlertInstance """ - super(AlertPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = await self._fetch_async() + return AlertInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of AlertInstance + Asynchronous coroutine to fetch the AlertInstance and return response metadata - :param dict payload: Payload response from the API - :returns: twilio.rest.monitor.v1.alert.AlertInstance - :rtype: twilio.rest.monitor.v1.alert.AlertInstance + :returns: ApiResponse with instance, status code, and headers """ - return AlertInstance(self._version, payload, ) + payload, status_code, headers = await self._fetch_async() + instance = AlertInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 AlertContext(InstanceContext): - """ """ +class AlertPage(Page): - def __init__(self, version, sid): + def get_instance(self, payload: Dict[str, Any]) -> AlertInstance: """ - Initialize the AlertContext - - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch + Build an instance of AlertInstance - :returns: twilio.rest.monitor.v1.alert.AlertContext - :rtype: twilio.rest.monitor.v1.alert.AlertContext + :param payload: Payload response from the API """ - super(AlertContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Alerts/{sid}'.format(**self._solution) + return AlertInstance(self._version, payload) - def fetch(self): + def __repr__(self) -> str: """ - Fetch the AlertInstance + Provide a friendly representation - :returns: The fetched AlertInstance - :rtype: twilio.rest.monitor.v1.alert.AlertInstance + :returns: Machine friendly representation """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + return "" - return AlertInstance(self._version, payload, sid=self._solution['sid'], ) - def __repr__(self): - """ - Provide a friendly representation +class AlertList(ListResource): - :returns: Machine friendly representation - :rtype: str + def __init__(self, version: Version): """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Initialize the AlertList + :param version: Version that contains the resource -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'), - } + """ + super().__init__(version) - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + self._uri = "/Alerts" - @property - def _proxy(self): + def stream( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AlertInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Streams AlertInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :returns: 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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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( + log_level=log_level, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) - @property - def alert_text(self): - """ - :returns: The text of the alert - :rtype: unicode - """ - return self._properties['alert_text'] + return self._version.stream(page, limits["limit"]) - @property - def api_version(self): - """ - :returns: The API version used when the alert was generated - :rtype: unicode + async def stream_async( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AlertInstance]: """ - return self._properties['api_version'] + 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. - @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 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) - @property - def date_generated(self): - """ - :returns: The date and time when the alert was generated specified in ISO 8601 format - :rtype: datetime + :returns: Generator that will yield up to limit results """ - return self._properties['date_generated'] + 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"], + ) - @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'] + return self._version.stream_async(page, limits["limit"]) - @property - def error_code(self): + def stream_with_http_info( + 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, + ) -> tuple: """ - :returns: The error code for the condition that generated the alert - :rtype: unicode - """ - return self._properties['error_code'] + Streams AlertInstance and returns headers from first page - @property - def log_level(self): - """ - :returns: The log level - :rtype: unicode - """ - return self._properties['log_level'] - @property - def more_info(self): - """ - :returns: The URL of the page in our Error Dictionary with more information about the error condition - :rtype: unicode - """ - return self._properties['more_info'] + :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) - @property - def request_method(self): - """ - :returns: The method used by the request that generated the alert - :rtype: unicode + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['request_method'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + log_level=log_level, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) - @property - def request_url(self): - """ - :returns: The URL of the request that generated the alert - :rtype: unicode - """ - return self._properties['request_url'] + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - @property - def request_variables(self): - """ - :returns: The variables passed in the request that generated the alert - :rtype: unicode + async def stream_with_http_info_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, + ) -> tuple: """ - return self._properties['request_variables'] + Asynchronously streams AlertInstance and returns headers from first page - @property - def resource_sid(self): - """ - :returns: The SID of the resource for which the alert was generated - :rtype: unicode - """ - return self._properties['resource_sid'] - @property - def response_body(self): + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The response body of the request that generated the alert - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + log_level=log_level, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - return self._properties['response_body'] + 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 response_headers(self): + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + log_level=log_level, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AlertInstance]: """ - :returns: The response headers of the request that generated the alert - :rtype: unicode + Asynchronously lists AlertInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + log_level=log_level, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists AlertInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + log_level=log_level, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists AlertInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + log_level=log_level, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['response_headers'] + Retrieve a single page of AlertInstance records from the API. + Request is executed immediately - @property - def sid(self): + :param log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AlertInstance """ - :returns: The unique string that identifies the resource - :rtype: unicode + data = values.of( + { + "LogLevel": log_level, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AlertPage(self._version, response) + + async def page_async( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AlertPage: + """ + Asynchronously retrieve a single page of AlertInstance records from the API. + Request is executed immediately + + :param log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AlertInstance """ - return self._properties['sid'] + 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 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 AlertPage(self._version, response) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AlertPage, status code, and headers + """ + data = values.of( + { + "LogLevel": log_level, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AlertPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AlertPage, status code, and headers + """ + data = values.of( + { + "LogLevel": log_level, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AlertPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> AlertPage: """ - :returns: The absolute URL of the Alert resource - :rtype: unicode + Retrieve a specific page of AlertInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AlertInstance """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return AlertPage(self._version, response) - @property - def request_headers(self): + async def get_page_async(self, target_url: str) -> AlertPage: """ - :returns: The request headers of the request that generated the alert - :rtype: unicode + Asynchronously retrieve a specific page of AlertInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AlertInstance """ - 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 f7786a5d8c..e568c814e1 100644 --- a/twilio/rest/monitor/v1/event.py +++ b/twilio/rest/monitor/v1/event.py @@ -1,455 +1,892 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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, + } - def __init__(self, version): + self._context: Optional[EventContext] = None + + @property + def _proxy(self) -> "EventContext": """ - Initialize the EventList + 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: EventContext for this EventInstance + """ + if self._context is None: + self._context = EventContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.monitor.v1.event.EventList - :rtype: twilio.rest.monitor.v1.event.EventList + def fetch(self) -> "EventInstance": """ - super(EventList, self).__init__(version) + Fetch the EventInstance - # Path Solution - self._solution = {} - self._uri = '/Events'.format(**self._solution) - 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): + :returns: The fetched 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 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) + return self._proxy.fetch() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.monitor.v1.event.EventInstance] + async def fetch_async(self) -> "EventInstance": """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine to fetch the EventInstance - page = self.page( - actor_sid=actor_sid, - event_type=event_type, - resource_sid=resource_sid, - source_ip_address=source_ip_address, - start_date=start_date, - end_date=end_date, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched EventInstance + """ + return await self._proxy.fetch_async() - 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Lists EventInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Fetch the EventInstance with HTTP info - :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) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.monitor.v1.event.EventInstance] + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream( - actor_sid=actor_sid, - event_type=event_type, - resource_sid=resource_sid, - source_ip_address=source_ip_address, - start_date=start_date, - end_date=end_date, - limit=limit, - page_size=page_size, - )) + return self._proxy.fetch_with_http_info() - 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of EventInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the EventInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> 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, - }) + Provide a friendly representation - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - return EventPage(self._version, response, self._solution) - def get_page(self, target_url): +class EventContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - Retrieve a specific page of EventInstance records from the API. - Request is executed immediately + Initialize the EventContext - :param str target_url: API-generated URL for the requested results page + :param version: Version that contains the resource + :param sid: The SID of the Event resource to fetch. + """ + super().__init__(version) - :returns: Page of EventInstance - :rtype: twilio.rest.monitor.v1.event.EventPage + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Events/{sid}".format(**self._solution) + + def _fetch(self) -> tuple: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) - return EventPage(self._version, response, self._solution) + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def get(self, sid): + def fetch(self) -> EventInstance: """ - Constructs a EventContext + 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, ) + payload, _, _ = self._fetch() + return EventInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a EventContext + Fetch the EventInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return EventContext(self._version, sid=sid, ) + payload, status_code, headers = self._fetch() + instance = EventInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class EventPage(Page): - """ """ + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + async def fetch_async(self) -> EventInstance: """ - Initialize the EventPage + Asynchronous coroutine to fetch the EventInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.monitor.v1.event.EventPage - :rtype: twilio.rest.monitor.v1.event.EventPage + :returns: The fetched EventInstance """ - super(EventPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = await self._fetch_async() + return EventInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of EventInstance + Asynchronous coroutine to fetch the EventInstance and return response metadata - :param dict payload: Payload response from the API - :returns: twilio.rest.monitor.v1.event.EventInstance - :rtype: twilio.rest.monitor.v1.event.EventInstance + :returns: ApiResponse with instance, status code, and headers """ - return EventInstance(self._version, payload, ) + payload, status_code, headers = await self._fetch_async() + instance = EventInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 EventContext(InstanceContext): - """ """ +class EventPage(Page): - def __init__(self, version, sid): + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: """ - Initialize the EventContext - - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch + Build an instance of EventInstance - :returns: twilio.rest.monitor.v1.event.EventContext - :rtype: twilio.rest.monitor.v1.event.EventContext + :param payload: Payload response from the API """ - super(EventContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Events/{sid}'.format(**self._solution) + return EventInstance(self._version, payload) - def fetch(self): + def __repr__(self) -> str: """ - Fetch the EventInstance + Provide a friendly representation - :returns: The fetched EventInstance - :rtype: twilio.rest.monitor.v1.event.EventInstance + :returns: Machine friendly representation """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + return "" - return EventInstance(self._version, payload, sid=self._solution['sid'], ) - def __repr__(self): - """ - Provide a friendly representation +class EventList(ListResource): - :returns: Machine friendly representation - :rtype: str + def __init__(self, version: Version): """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Initialize the EventList + :param version: Version that contains the resource -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'), - } + """ + super().__init__(version) - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + self._uri = "/Events" - @property - def _proxy(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]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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: EventContext for this EventInstance - :rtype: twilio.rest.monitor.v1.event.EventContext - """ - if self._context is None: - self._context = EventContext(self._version, sid=self._solution['sid'], ) - return self._context + :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) - @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( + 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"], + ) - @property - def actor_sid(self): - """ - :returns: The SID of the actor that caused the event, if available - :rtype: unicode - """ - return self._properties['actor_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. - @property - def actor_type(self): - """ - :returns: The type of actor that caused the event - :rtype: unicode - """ - return self._properties['actor_type'] + :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) - @property - def description(self): - """ - :returns: A description of the event - :rtype: unicode + :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( + 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"], + ) - @property - def event_data(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams EventInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: A JSON string that represents an object with additional data about the event - :rtype: dict - """ - return self._properties['event_data'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) - @property - def event_date(self): - """ - :returns: The ISO 8601 date and time in GMT when the event was recorded - :rtype: datetime + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams EventInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['event_date'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) - @property - def event_type(self): - """ - :returns: The event's type - :rtype: unicode + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - return self._properties['event_type'] + 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 resource_sid(self): - """ - :returns: The SID of the resource that was affected - :rtype: unicode - """ - return self._properties['resource_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 resource_type(self): - """ - :returns: The type of resource that was affected - :rtype: unicode - """ - return self._properties['resource_type'] + 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. - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists EventInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists EventInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['sid'] + Retrieve a single page of EventInstance records from the API. + Request is executed immediately - @property - def source(self): + :param actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance """ - :returns: The originating system or interface that caused the event - :rtype: unicode + data = values.of( + { + "ActorSid": actor_sid, + "EventType": event_type, + "ResourceSid": resource_sid, + "SourceIpAddress": source_ip_address, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response) + + async def page_async( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Asynchronously retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance """ - return self._properties['source'] + 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 source_ip_address(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 EventPage(self._version, response) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventPage, status code, and headers + """ + data = values.of( + { + "ActorSid": actor_sid, + "EventType": event_type, + "ResourceSid": resource_sid, + "SourceIpAddress": source_ip_address, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EventPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventPage, status code, and headers + """ + data = values.of( + { + "ActorSid": actor_sid, + "EventType": event_type, + "ResourceSid": resource_sid, + "SourceIpAddress": source_ip_address, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EventPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> EventPage: """ - :returns: The IP address of the source - :rtype: unicode + Retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance """ - return self._properties['source_ip_address'] + response = 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 9ccea9acf3..9bbd8bd0fc 100644 --- a/twilio/rest/notify/v1/credential.py +++ b/twilio/rest/notify/v1/credential.py @@ -1,435 +1,907 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the Credential resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Credential resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the Credential resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } - def __init__(self, version): + self._context: Optional[CredentialContext] = None + + @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 + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.notify.v1.credential.CredentialList - :rtype: twilio.rest.notify.v1.credential.CredentialList + def delete(self) -> bool: """ - super(CredentialList, self).__init__(version) + Deletes the CredentialInstance - # Path Solution - self._solution = {} - self._uri = '/Credentials'.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.notify.v1.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.credential.CredentialInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "CredentialInstance": """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + 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 self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance - return CredentialPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched CredentialInstance """ - Retrieve a specific page of CredentialInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info - :returns: Page of CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info - return CredentialPage(self._version, response, self._solution) - 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: ApiResponse with instance, status code, and headers """ - Create the CredentialInstance + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance - :param 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 + :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 - :rtype: twilio.rest.notify.v1.credential.CredentialInstance + :returns: The updated CredentialInstance """ - data = values.of({ - 'Type': type, - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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 - return CredentialInstance(self._version, payload, ) + :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(self, sid): + :returns: The updated CredentialInstance """ - Constructs a CredentialContext + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - :param sid: The unique string that identifies the resource + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. - :returns: twilio.rest.notify.v1.credential.CredentialContext - :rtype: twilio.rest.notify.v1.credential.CredentialContext + :returns: ApiResponse with instance, status code, and headers """ - return CredentialContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - def __call__(self, sid): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Constructs a CredentialContext + Asynchronous coroutine to update the CredentialInstance with HTTP info - :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 certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. - :returns: twilio.rest.notify.v1.credential.CredentialContext - :rtype: twilio.rest.notify.v1.credential.CredentialContext + :returns: ApiResponse with instance, status code, and headers """ - return CredentialContext(self._version, sid=sid, ) + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class CredentialContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the CredentialPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the CredentialContext - :returns: twilio.rest.notify.v1.credential.CredentialPage - :rtype: twilio.rest.notify.v1.credential.CredentialPage + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. """ - super(CredentialPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of CredentialInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.notify.v1.credential.CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialInstance + def delete(self) -> bool: """ - return CredentialInstance(self._version, payload, ) + Deletes the CredentialInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the CredentialInstance and return response metadata -class CredentialContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the CredentialContext - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource + headers = values.of({}) - :returns: twilio.rest.notify.v1.credential.CredentialContext - :rtype: twilio.rest.notify.v1.credential.CredentialContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(CredentialContext, self).__init__(version) + Asynchronous coroutine that deletes the CredentialInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: """ Fetch the CredentialInstance + :returns: The fetched CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance and return response metadata - 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): + :returns: ApiResponse with instance, status code, and headers """ - Update the CredentialInstance + payload, status_code, headers = self._fetch() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :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 + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: The updated CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ - 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, ) + headers = values.of({}) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CredentialInstance: """ - Deletes the CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched CredentialInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, _, _ = await self._fetch_async() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the CredentialInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + payload, status_code, headers = await self._fetch_async() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + Returns: + tuple: (payload, status_code, headers) + """ -class CredentialInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + 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({}) - class PushService(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - def __init__(self, version, payload, sid=None): + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - Initialize the CredentialInstance + Update the CredentialInstance - :returns: twilio.rest.notify.v1.credential.CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialInstance + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The updated CredentialInstance """ - super(CredentialInstance, self).__init__(version) + payload, _, _ = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CredentialInstance and return response metadata - # 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'), - } + :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. - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - 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 - :rtype: twilio.rest.notify.v1.credential.CredentialContext + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - if self._context is None: - self._context = CredentialContext(self._version, sid=self._solution['sid'], ) - return self._context + Asynchronous coroutine to update the CredentialInstance - @property - def sid(self): + :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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['sid'] + Asynchronous coroutine to update the CredentialInstance and return response metadata - @property - def account_sid(self): + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Provide a friendly representation + + :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 friendly_name(self): + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Build an instance of CredentialInstance + + :param payload: Payload response from the API """ - return self._properties['friendly_name'] - @property - def type(self): + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: """ - :returns: The Credential type, one of `gcm`, `fcm`, or `apn` - :rtype: CredentialInstance.PushService + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['type'] + return "" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource - @property - def sandbox(self): """ - :returns: [APN only] Whether to send the credential to sandbox APNs - :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, + ) -> tuple: """ - return self._properties['sandbox'] + Internal helper for create operation - @property - def date_created(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['date_created'] + Create the CredentialInstance - @property - def date_updated(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 RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Create the CredentialInstance and return response metadata - @property - def url(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: ApiResponse with instance, status code, and headers """ - :returns: The absolute URL of the Credential resource - :rtype: unicode + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: """ - return self._properties['url'] + Internal async helper for create operation - def fetch(self): + Returns: + tuple: (payload, status_code, headers) """ - Fetch the CredentialInstance - :returns: The fetched CredentialInstance - :rtype: twilio.rest.notify.v1.credential.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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._proxy.fetch() + Asynchronously create the CredentialInstance - 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 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 """ - Update the CredentialInstance + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata - :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 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 updated CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialInstance + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.update( + payload, status_code, headers = await self._create_async( + type=type, friendly_name=friendly_name, certificate=certificate, private_key=private_key, @@ -437,22 +909,394 @@ def update(self, friendly_name=values.unset, certificate=values.unset, api_key=api_key, secret=secret, ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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. - def delete(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 """ - Deletes the CredentialInstance + limits = self._version.read_limits(limit, page_size) + page = self.page(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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: """ - return self._proxy.delete() + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 6276654f56..629a7f2ae2 100644 --- a/twilio/rest/notify/v1/service/__init__.py +++ b/twilio/rest/notify/v1/service/__init__.py @@ -1,623 +1,699 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +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" + ) - def __init__(self, version): - """ - Initialize the ServiceList + self._solution = { + "sid": sid or self.sid, + } - :param Version version: Version that contains the resource + 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): + :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 + 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 + def delete(self) -> bool: """ - data = values.of({ - 'FriendlyName': friendly_name, - 'ApnCredentialSid': apn_credential_sid, - 'GcmCredentialSid': gcm_credential_sid, - 'MessagingServiceSid': messaging_service_sid, - 'FacebookMessengerPageId': facebook_messenger_page_id, - 'DefaultApnNotificationProtocolVersion': default_apn_notification_protocol_version, - 'DefaultGcmNotificationProtocolVersion': default_gcm_notification_protocol_version, - 'FcmCredentialSid': fcm_credential_sid, - 'DefaultFcmNotificationProtocolVersion': default_fcm_notification_protocol_version, - 'LogEnabled': log_enabled, - 'AlexaSkillId': alexa_skill_id, - 'DefaultAlexaNotificationProtocolVersion': default_alexa_notification_protocol_version, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + Deletes the ServiceInstance - return ServiceInstance(self._version, payload, ) - def stream(self, friendly_name=values.unset, 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 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) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.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(friendly_name=friendly_name, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, friendly_name=values.unset, limit=None, page_size=None): + def delete_with_http_info(self) -> ApiResponse: """ - Lists ServiceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the ServiceInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(friendly_name=friendly_name, limit=limit, page_size=page_size, )) + return self._proxy.delete_with_http_info() - def page(self, friendly_name=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the ServiceInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - data = values.of({ - 'FriendlyName': friendly_name, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return await self._proxy.delete_with_http_info_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return ServicePage(self._version, response, self._solution) - - def get_page(self, target_url): + def fetch(self) -> "ServiceInstance": """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately + Fetch the ServiceInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServicePage + :returns: The fetched ServiceInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ServicePage(self._version, response, self._solution) + return self._proxy.fetch() - def get(self, sid): + async def fetch_async(self) -> "ServiceInstance": """ - Constructs a ServiceContext + Asynchronous coroutine to fetch the ServiceInstance - :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 """ - return ServiceContext(self._version, sid=sid, ) + return await self._proxy.fetch_async() - def __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a ServiceContext + Fetch the ServiceInstance with HTTP info - :param sid: The unique string that identifies the resource - :returns: twilio.rest.notify.v1.service.ServiceContext - :rtype: twilio.rest.notify.v1.service.ServiceContext + :returns: ApiResponse with instance, status code, and headers """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.fetch_with_http_info() - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the ServiceInstance with HTTP info - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - return '' + return await self._proxy.fetch_with_http_info_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 -class ServicePage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :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 __init__(self, version, response, solution): + :returns: The updated ServiceInstance """ - Initialize the ServicePage + 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, + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API + 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: twilio.rest.notify.v1.service.ServicePage - :rtype: twilio.rest.notify.v1.service.ServicePage + :returns: The updated ServiceInstance """ - super(ServicePage, self).__init__(version, response) + 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, + ) - # Path Solution - self._solution = solution + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) - def get_instance(self, payload): - """ - Build an instance of ServiceInstance + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) - :param dict payload: Payload response from the API + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + return self._proxy.bindings - :returns: twilio.rest.notify.v1.service.ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServiceInstance + @property + def notifications(self) -> NotificationList: + """ + Access the notifications """ - return ServiceInstance(self._version, payload, ) + 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 ServiceContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, sid): + def __init__(self, version: Version, sid: str): """ Initialize the ServiceContext - :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 + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - super(ServiceContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) - - # Dependents - self._bindings = None - self._notifications = None + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) - def delete(self): - """ - Deletes the ServiceInstance + self._bindings: Optional[BindingList] = None + self._notifications: Optional[NotificationList] = None - :returns: True if delete succeeds, False otherwise - :rtype: bool + def _delete(self) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for delete operation - def fetch(self): + Returns: + tuple: (success_boolean, status_code, headers) """ - Fetch the ServiceInstance - :returns: The fetched ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServiceInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + headers = values.of({}) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - 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): + def delete(self) -> bool: """ - 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 + Deletes the ServiceInstance - :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'], ) - @property - def bindings(self): + :returns: True if delete succeeds, False otherwise """ - Access the bindings + success, _, _ = self._delete() + return success - :returns: twilio.rest.notify.v1.service.binding.BindingList - :rtype: twilio.rest.notify.v1.service.binding.BindingList + def delete_with_http_info(self) -> ApiResponse: """ - if self._bindings is None: - self._bindings = BindingList(self._version, service_sid=self._solution['sid'], ) - return self._bindings + Deletes the ServiceInstance and return response metadata - @property - def notifications(self): - """ - Access the notifications - :returns: twilio.rest.notify.v1.service.notification.NotificationList - :rtype: twilio.rest.notify.v1.service.notification.NotificationList + :returns: ApiResponse with success boolean, status code, and headers """ - if self._notifications is None: - self._notifications = NotificationList(self._version, service_sid=self._solution['sid'], ) - return self._notifications + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __repr__(self): + async def _delete_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for delete operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (success_boolean, status_code, headers) """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) -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'), - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - @property - def _proxy(self): + async def delete_async(self) -> bool: """ - 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 that deletes the ServiceInstance - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServiceContext - """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: True if delete succeeds, False otherwise """ - return self._properties['sid'] + success, _, _ = await self._delete_async() + return success - @property - def account_sid(self): + async def delete_with_http_info_async(self) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + Asynchronous coroutine that deletes the ServiceInstance and return response metadata - @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 + :returns: ApiResponse with success boolean, status code, and headers """ - return self._properties['date_created'] + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + def _fetch(self) -> tuple: """ - return self._properties['date_updated'] + Internal helper for fetch operation - @property - def apn_credential_sid(self): - """ - :returns: The SID of the Credential to use for APN Bindings - :rtype: unicode + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['apn_credential_sid'] - @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'] + headers = values.of({}) - @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'] + headers["Accept"] = "application/json" - @property - def messaging_service_sid(self): - """ - :returns: The SID of the Messaging Service to use for SMS Bindings - :rtype: unicode - """ - return self._properties['messaging_service_sid'] + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - @property - def facebook_messenger_page_id(self): - """ - :returns: Deprecated - :rtype: unicode + def fetch(self) -> ServiceInstance: """ - return self._properties['facebook_messenger_page_id'] + Fetch the ServiceInstance - @property - def default_apn_notification_protocol_version(self): - """ - :returns: The protocol version to use for sending APNS notifications - :rtype: unicode - """ - 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 + :returns: The fetched ServiceInstance """ - return self._properties['default_gcm_notification_protocol_version'] + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - @property - def default_fcm_notification_protocol_version(self): - """ - :returns: The protocol version to use for sending FCM notifications - :rtype: unicode + def fetch_with_http_info(self) -> ApiResponse: """ - return self._properties['default_fcm_notification_protocol_version'] + Fetch the ServiceInstance and return response metadata - @property - def log_enabled(self): - """ - :returns: Whether to log notifications - :rtype: bool - """ - return self._properties['log_enabled'] - @property - def url(self): + :returns: ApiResponse with instance, status code, and headers """ - :returns: The absolute URL of the Service resource - :rtype: unicode - """ - return self._properties['url'] + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def links(self): - """ - :returns: The URLs of the resources related to the service - :rtype: unicode + async def _fetch_async(self) -> tuple: """ - return self._properties['links'] + Internal async helper for fetch operation - @property - def alexa_skill_id(self): - """ - :returns: Deprecated - :rtype: unicode + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['alexa_skill_id'] - @property - def default_alexa_notification_protocol_version(self): - """ - :returns: Deprecated - :rtype: unicode - """ - return self._properties['default_alexa_notification_protocol_version'] + headers = values.of({}) + + headers["Accept"] = "application/json" - def delete(self): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + 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._proxy.delete() + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Fetch the ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance and return response metadata - :returns: The fetched ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServiceInstance + + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.fetch() + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" - 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): + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 - :rtype: twilio.rest.notify.v1.service.ServiceInstance """ - return self._proxy.update( + payload, _, _ = self._update( friendly_name=friendly_name, apn_credential_sid=apn_credential_sid, gcm_credential_sid=gcm_credential_sid, @@ -633,33 +709,1047 @@ def update(self, friendly_name=values.unset, apn_credential_sid=values.unset, delivery_callback_url=delivery_callback_url, delivery_callback_enabled=delivery_callback_enabled, ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + if self._bindings is None: + self._bindings = BindingList( + self._version, + self._solution["sid"], + ) + return self._bindings + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + if self._notifications is None: + self._notifications = NotificationList( + self._version, + self._solution["sid"], + ) + return self._notifications + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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: 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The created ServiceInstance + """ + payload, _, _ = self._create( + 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 ServiceInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + 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, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_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, + ) + return ServiceInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_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, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the Service resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the Service resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ServicePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ServicePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) - @property - def bindings(self): - """ - Access the bindings - - :returns: twilio.rest.notify.v1.service.binding.BindingList - :rtype: twilio.rest.notify.v1.service.binding.BindingList - """ - return self._proxy.bindings - - @property - def notifications(self): - """ - Access the notifications - - :returns: twilio.rest.notify.v1.service.notification.NotificationList - :rtype: twilio.rest.notify.v1.service.notification.NotificationList - """ - return self._proxy.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) + return "" diff --git a/twilio/rest/notify/v1/service/binding.py b/twilio/rest/notify/v1/service/binding.py index 620fca6cf6..e380730645 100644 --- a/twilio/rest/notify/v1/service/binding.py +++ b/twilio/rest/notify/v1/service/binding.py @@ -1,510 +1,1182 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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, + } - :returns: twilio.rest.notify.v1.service.binding.BindingList - :rtype: twilio.rest.notify.v1.service.binding.BindingList + self._context: Optional[BindingContext] = None + + @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 """ - 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, - }) + 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 BindingInstance - return BindingInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, start_date=values.unset, end_date=values.unset, - identity=values.unset, tag=values.unset, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - Streams BindingInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + return await self._proxy.delete_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. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BindingInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.service.binding.BindingInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.delete_with_http_info() - page = self.page( - start_date=start_date, - end_date=end_date, - identity=identity, - tag=tag, - page_size=limits['page_size'], - ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, start_date=values.unset, end_date=values.unset, - identity=values.unset, tag=values.unset, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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.delete_with_http_info_async() + + def fetch(self) -> "BindingInstance": + """ + 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. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.service.binding.BindingInstance] + :returns: The fetched BindingInstance """ - return list(self.stream( - start_date=start_date, - end_date=end_date, - identity=identity, - tag=tag, - limit=limit, - page_size=page_size, - )) + return self._proxy.fetch() - 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): + async def fetch_async(self) -> "BindingInstance": """ - Retrieve a single page of BindingInstance records from the API. - Request is executed immediately + Asynchronous coroutine to 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 str page_token: PageToken provided by the API - :param int page_number: 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 + :returns: The fetched BindingInstance """ - data = values.of({ - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'Identity': serialize.map(identity, lambda e: e), - 'Tag': serialize.map(tag, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance with HTTP info - return BindingPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of BindingInstance records from the API. - Request is executed immediately + return self._proxy.fetch_with_http_info() - :param str target_url: API-generated URL for the requested results page + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BindingInstance with HTTP info - :returns: Page of BindingInstance - :rtype: twilio.rest.notify.v1.service.binding.BindingPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.fetch_with_http_info_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 unique string that identifies the resource +class BindingContext(InstanceContext): - :returns: twilio.rest.notify.v1.service.binding.BindingContext - :rtype: twilio.rest.notify.v1.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/notify/api/service-resource) to fetch the resource from. + :param sid: The Twilio-provided string that uniquely identifies the Binding resource to fetch. """ - Constructs a BindingContext + 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}/Bindings/{sid}".format(**self._solution) - :returns: twilio.rest.notify.v1.service.binding.BindingContext - :rtype: twilio.rest.notify.v1.service.binding.BindingContext + def _delete(self) -> tuple: """ - return BindingContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Internal helper for delete operation - def __repr__(self): + Returns: + tuple: (success_boolean, status_code, headers) """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return '' + Deletes the BindingInstance -class BindingPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success - def __init__(self, version, response, solution): + def delete_with_http_info(self) -> ApiResponse: """ - Initialize the BindingPage + Deletes the BindingInstance and return response metadata - :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.binding.BindingPage - :rtype: twilio.rest.notify.v1.service.binding.BindingPage + :returns: ApiResponse with success boolean, status code, and headers """ - super(BindingPage, self).__init__(version, response) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - # Path Solution - self._solution = solution + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation - def get_instance(self, payload): + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of BindingInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.notify.v1.service.binding.BindingInstance - :rtype: twilio.rest.notify.v1.service.binding.BindingInstance - """ - return BindingInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __repr__(self): + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the BindingInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance and return response metadata -class BindingContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, service_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the BindingContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.notify.v1.service.binding.BindingContext - :rtype: twilio.rest.notify.v1.service.binding.BindingContext + Returns: + tuple: (payload, status_code, headers) """ - 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({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> BindingInstance: """ Fetch the BindingInstance + :returns: The fetched BindingInstance - :rtype: twilio.rest.notify.v1.service.binding.BindingInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - + payload, _, _ = self._fetch() 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 fetch_with_http_info(self) -> ApiResponse: """ - Deletes the BindingInstance + Fetch the BindingInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = self._fetch() + instance = BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) -class BindingInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" - class BindingType(object): - APN = "apn" - GCM = "gcm" - SMS = "sms" - FCM = "fcm" - FACEBOOK_MESSENGER = "facebook-messenger" - ALEXA = "alexa" + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - 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'), - } + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): + :returns: The fetched BindingInstance """ - 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._fetch_async() + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - :returns: BindingContext for this BindingInstance - :rtype: twilio.rest.notify.v1.service.binding.BindingContext + async def fetch_with_http_info_async(self) -> ApiResponse: """ - if self._context is None: - self._context = BindingContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Asynchronous coroutine to fetch the BindingInstance and return response metadata - @property - def sid(self): + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, status_code, headers = await self._fetch_async() + instance = BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - 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 + 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: """ - return self._properties['account_sid'] + Build an instance of BindingInstance - @property - def service_sid(self): + :param payload: Payload response from the API """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + + return BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: """ - return self._properties['service_sid'] + Provide a friendly representation - @property - def credential_sid(self): + :returns: Machine friendly representation """ - :returns: The SID of the Credential resource to be used to send notifications to this Binding - :rtype: unicode + return "" + + +class BindingList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - return self._properties['credential_sid'] + Initialize the BindingList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/notify/api/service-resource) to read the resource from. - @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 = { + "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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Identity": identity, + "BindingType": binding_type, + "Address": address, + "Tag": serialize.map(tag, lambda e: e), + "NotificationProtocolVersion": notification_protocol_version, + "CredentialSid": credential_sid, + "Endpoint": endpoint, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._properties['date_created'] + Create the BindingInstance - @property - def date_updated(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/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 """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + payload, _, _ = self._create( + identity=identity, + binding_type=binding_type, + address=address, + tag=tag, + notification_protocol_version=notification_protocol_version, + credential_sid=credential_sid, + endpoint=endpoint, + ) + return BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the BindingInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + binding_type=binding_type, + address=address, + tag=tag, + notification_protocol_version=notification_protocol_version, + credential_sid=credential_sid, + endpoint=endpoint, + ) + instance = BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Identity": identity, + "BindingType": binding_type, + "Address": address, + "Tag": serialize.map(tag, lambda e: e), + "NotificationProtocolVersion": notification_protocol_version, + "CredentialSid": credential_sid, + "Endpoint": endpoint, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - return self._properties['date_updated'] + payload, _, _ = await self._create_async( + identity=identity, + binding_type=binding_type, + address=address, + tag=tag, + notification_protocol_version=notification_protocol_version, + credential_sid=credential_sid, + endpoint=endpoint, + ) + return BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def notification_protocol_version(self): + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the BindingInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + binding_type=binding_type, + address=address, + tag=tag, + notification_protocol_version=notification_protocol_version, + credential_sid=credential_sid, + endpoint=endpoint, + ) + instance = BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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]: """ - :returns: The protocol version to use to send the notification - :rtype: unicode + Streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['notification_protocol_version'] + 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 endpoint(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BindingInstance]: """ - :returns: Deprecated - :rtype: unicode + Asynchronously streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['endpoint'] + 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 identity(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: """ - :returns: The `identity` value that identifies the new resource's User - :rtype: unicode + Streams BindingInstance and returns headers from first page + + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['identity'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + page_size=limits["page_size"], + ) - @property - def binding_type(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - :returns: The type of the Binding - :rtype: unicode + Asynchronously streams BindingInstance and returns headers from first page + + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['binding_type'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + page_size=limits["page_size"], + ) - @property - def address(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 channel-specific address - :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 date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Asynchronously lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists BindingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists BindingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['address'] + Retrieve a single page of BindingInstance records from the API. + Request is executed immediately - @property - def tags(self): + :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 """ - :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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with BindingPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with BindingPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..a16ef7acf1 100644 --- a/twilio/rest/notify/v1/service/notification.py +++ b/twilio/rest/notify/v1/service/notification.py @@ -1,357 +1,520 @@ -# 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 + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + Twilio - Notify + This is the public Twilio REST API. -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) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of NotificationInstance - - :param dict payload: Payload response from the API + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" - :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'], ) +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse - def __repr__(self): - """ - Provide a friendly representation - - :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'] - - @property - def title(self): - """ - :returns: The notification title - :rtype: unicode - """ - return self._properties['title'] + Provide a friendly representation - @property - def body(self): - """ - :returns: The notification body text - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['body'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def sound(self): - """ - :returns: The name of the sound to be played for the notification - :rtype: unicode - """ - return self._properties['sound'] - @property - def action(self): - """ - :returns: The actions to display for the notification - :rtype: unicode - """ - return self._properties['action'] +class NotificationList(ListResource): - @property - def data(self): - """ - :returns: The custom key-value pairs of the notification's payload - :rtype: dict + def __init__(self, version: Version, service_sid: str): """ - return self._properties['data'] + Initialize the NotificationList - @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'] + :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 gcm(self): """ - :returns: The GCM-specific payload that overrides corresponding attributes in generic payload for GCM Bindings - :rtype: dict - """ - return self._properties['gcm'] + super().__init__(version) - @property - def fcm(self): - """ - :returns: The FCM-specific payload that overrides corresponding attributes in generic payload for FCM 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['fcm'] + Create the NotificationInstance - @property - def sms(self): - """ - :returns: The SMS-specific payload that overrides corresponding attributes in generic payload for SMS Bindings - :rtype: dict - """ - return self._properties['sms'] + :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 facebook_messenger(self): - """ - :returns: Deprecated - :rtype: dict + :returns: The created NotificationInstance """ - return self._properties['facebook_messenger'] + payload, _, _ = self._create( + body=body, + priority=priority, + ttl=ttl, + title=title, + sound=sound, + action=action, + data=data, + apn=apn, + gcm=gcm, + sms=sms, + facebook_messenger=facebook_messenger, + fcm=fcm, + segment=segment, + alexa=alexa, + to_binding=to_binding, + delivery_callback_url=delivery_callback_url, + identity=identity, + tag=tag, + ) + return NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the NotificationInstance and return response metadata + + :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :param priority: + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :param title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :param sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :param action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :param gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). + :param sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :param facebook_messenger: Deprecated. + :param fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :param segment: The Segment resource is deprecated. Use the `tag` parameter, instead. + :param alexa: Deprecated. + :param to_binding: The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. + :param delivery_callback_url: URL to send webhooks. + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. + :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + body=body, + priority=priority, + ttl=ttl, + title=title, + sound=sound, + action=action, + data=data, + apn=apn, + gcm=gcm, + sms=sms, + facebook_messenger=facebook_messenger, + fcm=fcm, + segment=segment, + alexa=alexa, + to_binding=to_binding, + delivery_callback_url=delivery_callback_url, + identity=identity, + tag=tag, + ) + instance = NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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): + payload, _, _ = await self._create_async( + body=body, + priority=priority, + ttl=ttl, + title=title, + sound=sound, + action=action, + data=data, + apn=apn, + gcm=gcm, + sms=sms, + facebook_messenger=facebook_messenger, + fcm=fcm, + segment=segment, + alexa=alexa, + to_binding=to_binding, + delivery_callback_url=delivery_callback_url, + identity=identity, + tag=tag, + ) + return NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the NotificationInstance and return response metadata + + :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :param priority: + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :param title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :param sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :param action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :param gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). + :param sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :param facebook_messenger: Deprecated. + :param fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :param segment: The Segment resource is deprecated. Use the `tag` parameter, instead. + :param alexa: Deprecated. + :param to_binding: The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. + :param delivery_callback_url: URL to send webhooks. + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. + :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + body=body, + priority=priority, + ttl=ttl, + title=title, + sound=sound, + action=action, + data=data, + apn=apn, + gcm=gcm, + sms=sms, + facebook_messenger=facebook_messenger, + fcm=fcm, + segment=segment, + alexa=alexa, + to_binding=to_binding, + delivery_callback_url=delivery_callback_url, + identity=identity, + tag=tag, + ) + instance = NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..d7b4b3ee8e --- /dev/null +++ b/twilio/rest/numbers/NumbersBase.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.numbers.v1 import V1 +from twilio.rest.numbers.v2 import V2 +from twilio.rest.numbers.v3 import V3 + + +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 + self._v3: Optional[V3] = 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 + + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Numbers + """ + 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/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..a3f3cc0847 --- /dev/null +++ b/twilio/rest/numbers/v1/__init__.py @@ -0,0 +1,158 @@ +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.embedded_session import EmbeddedSessionList +from twilio.rest.numbers.v1.porting_all_port_in import PortingAllPortInList +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.sender_id_registration import SenderIdRegistrationList +from twilio.rest.numbers.v1.signing_request_configuration import ( + SigningRequestConfigurationList, +) +from twilio.rest.numbers.v1.webhook import WebhookList + + +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_all_port_ins: Optional[PortingAllPortInList] = 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._sender_id_registrations: Optional[SenderIdRegistrationList] = None + self._signing_request_configurations: Optional[ + SigningRequestConfigurationList + ] = None + self._webhook: Optional[WebhookList] = 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 + + def embedded_sessions(self, bundle_sid: str, embedded_session_id: str = None): + """ + Access the EmbeddedSessionList resource + + :param bundle_sid: The unique identifier of the registration (BU-prefixed). + + :param embedded_session_id: Optional instance ID to directly access EmbeddedSessionContext + :returns: EmbeddedSessionList instance if embedded_session_id is None, otherwise EmbeddedSessionContext + """ + list_instance = EmbeddedSessionList(self, bundle_sid) + if embedded_session_id is not None: + return list_instance(embedded_session_id) + return list_instance + + @property + def porting_all_port_ins(self) -> PortingAllPortInList: + if self._porting_all_port_ins is None: + self._porting_all_port_ins = PortingAllPortInList(self) + return self._porting_all_port_ins + + @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 sender_id_registrations(self) -> SenderIdRegistrationList: + if self._sender_id_registrations is None: + self._sender_id_registrations = SenderIdRegistrationList(self) + return self._sender_id_registrations + + @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 + + @property + def webhook(self) -> WebhookList: + if self._webhook is None: + self._webhook = WebhookList(self) + return self._webhook + + 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..ed521218a5 --- /dev/null +++ b/twilio/rest/numbers/v1/bulk_eligibility.py @@ -0,0 +1,369 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BulkEligibilityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BulkEligibilityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BulkEligibilityInstance: + """ + Fetch the BulkEligibilityInstance + + + :returns: The fetched BulkEligibilityInstance + """ + payload, _, _ = self._fetch() + return BulkEligibilityInstance( + self._version, + payload, + request_id=self._solution["request_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BulkEligibilityInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BulkEligibilityInstance( + self._version, + payload, + request_id=self._solution["request_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> BulkEligibilityInstance: + """ + Asynchronous coroutine to fetch the BulkEligibilityInstance + + + :returns: The fetched BulkEligibilityInstance + """ + payload, _, _ = await self._fetch_async() + return BulkEligibilityInstance( + self._version, + payload, + request_id=self._solution["request_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BulkEligibilityInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BulkEligibilityInstance( + self._version, + payload, + request_id=self._solution["request_id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, body: Union[object, object] = values.unset + ) -> BulkEligibilityInstance: + """ + Create the BulkEligibilityInstance + + :param body: + + :returns: The created BulkEligibilityInstance + """ + payload, _, _ = self._create(body=body) + return BulkEligibilityInstance(self._version, payload) + + def create_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the BulkEligibilityInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body) + instance = BulkEligibilityInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> BulkEligibilityInstance: + """ + Asynchronously create the BulkEligibilityInstance + + :param body: + + :returns: The created BulkEligibilityInstance + """ + payload, _, _ = await self._create_async(body=body) + return BulkEligibilityInstance(self._version, payload) + + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the BulkEligibilityInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(body=body) + instance = BulkEligibilityInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..37d6f1c07d --- /dev/null +++ b/twilio/rest/numbers/v1/eligibility.py @@ -0,0 +1,153 @@ +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.api_response import ApiResponse + +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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, body: Union[object, object] = values.unset) -> EligibilityInstance: + """ + Create the EligibilityInstance + + :param body: + + :returns: The created EligibilityInstance + """ + payload, _, _ = self._create(body=body) + return EligibilityInstance(self._version, payload) + + def create_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the EligibilityInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body) + instance = EligibilityInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> EligibilityInstance: + """ + Asynchronously create the EligibilityInstance + + :param body: + + :returns: The created EligibilityInstance + """ + payload, _, _ = await self._create_async(body=body) + return EligibilityInstance(self._version, payload) + + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the EligibilityInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(body=body) + instance = EligibilityInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v1/embedded_session.py b/twilio/rest/numbers/v1/embedded_session.py new file mode 100644 index 0000000000..d047adc2ab --- /dev/null +++ b/twilio/rest/numbers/v1/embedded_session.py @@ -0,0 +1,230 @@ +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 +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class EmbeddedSessionInstance(InstanceResource): + + class NumbersV1CreateEmbeddedSessionRequest(object): + """ + :ivar theme_set_id: Theme ID for the Compliance Embeddable UI. Overrides the theme set during registration creation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.theme_set_id: Optional[str] = payload.get("themeSetId") + + def to_dict(self): + return { + "themeSetId": self.theme_set_id, + } + + """ + :ivar id: Registration identifier (BU-prefixed). + :ivar session_id: Session ID for the compliance embeddable. + :ivar session_token: Ephemeral session token for the compliance embeddable. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + bundle_sid: Optional[str] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.session_id: Optional[str] = payload.get("sessionId") + self.session_token: Optional[str] = payload.get("sessionToken") + + self._solution = { + "bundle_sid": bundle_sid or self.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 EmbeddedSessionList(ListResource): + + class NumbersV1CreateEmbeddedSessionRequest(object): + """ + :ivar theme_set_id: Theme ID for the Compliance Embeddable UI. Overrides the theme set during registration creation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.theme_set_id: Optional[str] = payload.get("themeSetId") + + def to_dict(self): + return { + "themeSetId": self.theme_set_id, + } + + def __init__(self, version: Version, bundle_sid: str): + """ + Initialize the EmbeddedSessionList + + :param version: Version that contains the resource + :param bundle_sid: The unique identifier of the registration (BU-prefixed). + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/SenderIdRegistrations/{bundle_sid}/EmbeddedSessions".format( + **self._solution + ) + + def _create( + self, + numbers_v1_create_embedded_session_request: NumbersV1CreateEmbeddedSessionRequest, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = numbers_v1_create_embedded_session_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + numbers_v1_create_embedded_session_request: NumbersV1CreateEmbeddedSessionRequest, + ) -> EmbeddedSessionInstance: + """ + Create the EmbeddedSessionInstance + + :param numbers_v1_create_embedded_session_request: + + :returns: The created EmbeddedSessionInstance + """ + payload, _, _ = self._create( + numbers_v1_create_embedded_session_request=numbers_v1_create_embedded_session_request + ) + return EmbeddedSessionInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def create_with_http_info( + self, + numbers_v1_create_embedded_session_request: NumbersV1CreateEmbeddedSessionRequest, + ) -> ApiResponse: + """ + Create the EmbeddedSessionInstance and return response metadata + + :param numbers_v1_create_embedded_session_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + numbers_v1_create_embedded_session_request=numbers_v1_create_embedded_session_request + ) + instance = EmbeddedSessionInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + numbers_v1_create_embedded_session_request: NumbersV1CreateEmbeddedSessionRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = numbers_v1_create_embedded_session_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + numbers_v1_create_embedded_session_request: NumbersV1CreateEmbeddedSessionRequest, + ) -> EmbeddedSessionInstance: + """ + Asynchronously create the EmbeddedSessionInstance + + :param numbers_v1_create_embedded_session_request: + + :returns: The created EmbeddedSessionInstance + """ + payload, _, _ = await self._create_async( + numbers_v1_create_embedded_session_request=numbers_v1_create_embedded_session_request + ) + return EmbeddedSessionInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_with_http_info_async( + self, + numbers_v1_create_embedded_session_request: NumbersV1CreateEmbeddedSessionRequest, + ) -> ApiResponse: + """ + Asynchronously create the EmbeddedSessionInstance and return response metadata + + :param numbers_v1_create_embedded_session_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + numbers_v1_create_embedded_session_request=numbers_v1_create_embedded_session_request + ) + instance = EmbeddedSessionInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v1/porting_all_port_in.py b/twilio/rest/numbers/v1/porting_all_port_in.py new file mode 100644 index 0000000000..3a2df49b13 --- /dev/null +++ b/twilio/rest/numbers/v1/porting_all_port_in.py @@ -0,0 +1,689 @@ +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 deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PortingAllPortInInstance(InstanceResource): + """ + :ivar port_in_request_sid: The SID of the Port-in request + :ivar port_in_request_status: Status of the Port In Request + :ivar status_last_updated_timestamp: The last updated timestamp of the request + :ivar phone_numbers_requested: Amount of phone numbers requested + :ivar phone_numbers_ported: Amount of phone numbers ported + :ivar suggested_action: Suggested action on this ticket + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.port_in_request_sid: Optional[str] = payload.get("port_in_request_sid") + self.port_in_request_status: Optional[str] = payload.get( + "port_in_request_status" + ) + self.status_last_updated_timestamp: Optional[str] = payload.get( + "status_last_updated_timestamp" + ) + self.phone_numbers_requested: Optional[int] = deserialize.integer( + payload.get("phone_numbers_requested") + ) + self.phone_numbers_ported: Optional[int] = deserialize.integer( + payload.get("phone_numbers_ported") + ) + self.suggested_action: Optional[str] = payload.get("suggested_action") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class PortingAllPortInPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PortingAllPortInInstance: + """ + Build an instance of PortingAllPortInInstance + + :param payload: Payload response from the API + """ + + return PortingAllPortInInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PortingAllPortInList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingAllPortInList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Porting/PortIn/PortInRequests" + + def stream( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PortingAllPortInInstance]: + """ + Streams PortingAllPortInInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain date + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PortingAllPortInInstance]: + """ + Asynchronously streams PortingAllPortInInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain date + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PortingAllPortInInstance and returns headers from first page + + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PortingAllPortInInstance and returns headers from first page + + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PortingAllPortInInstance]: + """ + Lists PortingAllPortInInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain 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( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PortingAllPortInInstance]: + """ + Asynchronously lists PortingAllPortInInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain 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( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PortingAllPortInInstance and returns headers from first page + + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PortingAllPortInInstance and returns headers from first page + + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PortingAllPortInPage: + """ + Retrieve a single page of PortingAllPortInInstance records from the API. + Request is executed immediately + + :param token: Page start token, if null then it will start from the beginning + :param size: Number of items per page + :param port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param port_in_request_status: Filter by Port In request status + :param created_before: Find all created before a certain date + :param created_after: Find all created after a certain 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 PortingAllPortInInstance + """ + data = values.of( + { + "Token": token, + "Size": size, + "PortInRequestSid": port_in_request_sid, + "PortInRequestStatus": port_in_request_status, + "CreatedBefore": created_before, + "CreatedAfter": 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 PortingAllPortInPage(self._version, response) + + async def page_async( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PortingAllPortInPage: + """ + Asynchronously retrieve a single page of PortingAllPortInInstance records from the API. + Request is executed immediately + + :param token: Page start token, if null then it will start from the beginning + :param size: Number of items per page + :param port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param port_in_request_status: Filter by Port In request status + :param created_before: Find all created before a certain date + :param created_after: Find all created after a certain 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 PortingAllPortInInstance + """ + data = values.of( + { + "Token": token, + "Size": size, + "PortInRequestSid": port_in_request_sid, + "PortInRequestStatus": port_in_request_status, + "CreatedBefore": created_before, + "CreatedAfter": created_after, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PortingAllPortInPage(self._version, response) + + def page_with_http_info( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param token: Page start token, if null then it will start from the beginning + :param size: Number of items per page + :param port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param port_in_request_status: Filter by Port In request status + :param created_before: Find all created before a certain date + :param created_after: Find all created after a certain 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: ApiResponse with PortingAllPortInPage, status code, and headers + """ + data = values.of( + { + "Token": token, + "Size": size, + "PortInRequestSid": port_in_request_sid, + "PortInRequestStatus": port_in_request_status, + "CreatedBefore": created_before, + "CreatedAfter": 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PortingAllPortInPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param token: Page start token, if null then it will start from the beginning + :param size: Number of items per page + :param port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param port_in_request_status: Filter by Port In request status + :param created_before: Find all created before a certain date + :param created_after: Find all created after a certain 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: ApiResponse with PortingAllPortInPage, status code, and headers + """ + data = values.of( + { + "Token": token, + "Size": size, + "PortInRequestSid": port_in_request_sid, + "PortInRequestStatus": port_in_request_status, + "CreatedBefore": created_before, + "CreatedAfter": 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PortingAllPortInPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> PortingAllPortInPage: + """ + Retrieve a specific page of PortingAllPortInInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PortingAllPortInInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PortingAllPortInPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PortingAllPortInPage: + """ + Asynchronously retrieve a specific page of PortingAllPortInInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PortingAllPortInInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PortingAllPortInPage(self._version, response) + + 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..53400a5fd0 --- /dev/null +++ b/twilio/rest/numbers/v1/porting_port_in.py @@ -0,0 +1,1047 @@ +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 +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.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): + + class NumbersV1PortingAddress(object): + """ + :ivar street: The street address, ex: 101 Spear St + :ivar street_2: The building information, ex : 5th floor. + :ivar city: The city name, ex: San Francisco. + :ivar state: The state name, ex: CA or California. Note this should match the losing carrier’s information exactly. So if they spell out the entire state’s name instead of abbreviating it, please do so. + :ivar zip: The zip code, ex: 94105. + :ivar country: The country, ex: USA. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.street: Optional[str] = payload.get("street") + self.street_2: Optional[str] = payload.get("street_2") + self.city: Optional[str] = payload.get("city") + self.state: Optional[str] = payload.get("state") + self.zip: Optional[str] = payload.get("zip") + self.country: Optional[str] = payload.get("country") + + def to_dict(self): + return { + "street": self.street, + "street_2": self.street_2, + "city": self.city, + "state": self.state, + "zip": self.zip, + "country": self.country, + } + + class NumbersV1PortingLosingCarrierInformation(object): + """ + :ivar customer_name: Customer name as it is registered with the losing carrier. This can be an individual or a business name depending on the customer type selected. + :ivar account_number: The account number of the customer for the losing carrier. Only require for mobile phone numbers. + :ivar account_telephone_number: The account phone number of the customer for the losing carrier. + :ivar address_sid: If you already have an Address SID that represents the address needed for the LOA, you can provide an Address SID instead of providing the address object in the request body. This will copy the address into the port in request. If changes are made to the Address SID after port in request creation, those changes will not be reflected in the port in request. + :ivar address: + :ivar authorized_representative: The first and last name of the person listed with the losing carrier who is authorized to make changes on the account. + :ivar authorized_representative_email: Email address of the person (owner of the number) who will sign the letter of authorization for the port in request. This email address should belong to the person named in as the authorized representative. + :ivar customer_type: The type of customer account in the losing carrier. This should either be: 'Individual' or 'Business'. + :ivar authorized_representative_katakana: + :ivar sub_municipality: + :ivar building: + :ivar katakana_name: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_name: Optional[str] = payload.get("customer_name") + self.account_number: Optional[str] = payload.get("account_number") + self.account_telephone_number: Optional[str] = payload.get( + "account_telephone_number" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.address: Optional[PortingPortInList.NumbersV1PortingAddress] = ( + payload.get("address") + ) + self.authorized_representative: Optional[str] = payload.get( + "authorized_representative" + ) + self.authorized_representative_email: Optional[str] = payload.get( + "authorized_representative_email" + ) + self.customer_type: Optional["PortingPortInInstance.str"] = payload.get( + "customer_type" + ) + self.authorized_representative_katakana: Optional[str] = payload.get( + "authorized_representative_katakana" + ) + self.sub_municipality: Optional[str] = payload.get("sub_municipality") + self.building: Optional[str] = payload.get("building") + self.katakana_name: Optional[str] = payload.get("katakana_name") + + def to_dict(self): + return { + "customer_name": self.customer_name, + "account_number": self.account_number, + "account_telephone_number": self.account_telephone_number, + "address_sid": self.address_sid, + "address": self.address.to_dict() if self.address is not None else None, + "authorized_representative": self.authorized_representative, + "authorized_representative_email": self.authorized_representative_email, + "customer_type": self.customer_type, + "authorized_representative_katakana": self.authorized_representative_katakana, + "sub_municipality": self.sub_municipality, + "building": self.building, + "katakana_name": self.katakana_name, + } + + class NumbersV1PortingPortInCreate(object): + """ + :ivar account_sid: Account Sid or subaccount where the phone number(s) will be Ported + :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 phone_numbers: List of phone numbers to be ported. Maximum of 1,000 phone numbers per request. + :ivar losing_carrier_information: + :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 bundle_sid: The bundle sid is an optional identifier to reference a group of regulatory documents for a port request. + :ivar portability_advance_carrier: A field only required for Japan port in requests. It is a unique identifier for the donor carrier service the line is being ported from. + :ivar auto_cancel_approval_numbers: Japan specific field, indicates the number of phone numbers to automatically approve for cancellation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.account_sid: Optional[str] = payload.get("account_sid") + self.documents: Optional[List[str]] = payload.get("documents") + self.phone_numbers: Optional[ + List[PortingPortInList.NumbersV1PortingPortInCreatePhoneNumbers] + ] = payload.get("phone_numbers") + self.losing_carrier_information: Optional[ + PortingPortInList.NumbersV1PortingLosingCarrierInformation + ] = payload.get("losing_carrier_information") + self.notification_emails: Optional[List[str]] = payload.get( + "notification_emails" + ) + self.target_port_in_date: Optional[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.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.portability_advance_carrier: Optional[str] = payload.get( + "portability_advance_carrier" + ) + self.auto_cancel_approval_numbers: Optional[str] = payload.get( + "auto_cancel_approval_numbers" + ) + + def to_dict(self): + return { + "account_sid": self.account_sid, + "documents": self.documents, + "phone_numbers": ( + [phone_numbers.to_dict() for phone_numbers in self.phone_numbers] + if self.phone_numbers is not None + else None + ), + "losing_carrier_information": ( + self.losing_carrier_information.to_dict() + if self.losing_carrier_information is not None + else None + ), + "notification_emails": self.notification_emails, + "target_port_in_date": self.target_port_in_date, + "target_port_in_time_range_start": self.target_port_in_time_range_start, + "target_port_in_time_range_end": self.target_port_in_time_range_end, + "bundle_sid": self.bundle_sid, + "portability_advance_carrier": self.portability_advance_carrier, + "auto_cancel_approval_numbers": self.auto_cancel_approval_numbers, + } + + class NumbersV1PortingPortInCreatePhoneNumbers(object): + """ + :ivar phone_number: Phone number to be ported. This must be in the E164 Format. + :ivar pin: Some losing carriers require a PIN to authorize the port of a phone number. If the phone number is a US mobile phone number, the PIN is mandatory to process a porting request. Other carriers and number types may also require a PIN, you'll need to contact the losing carrier to determine what your phone number's PIN is. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_number: Optional[str] = payload.get("phone_number") + self.pin: Optional[str] = payload.get("pin") + + def to_dict(self): + return { + "phone_number": self.phone_number, + "pin": self.pin, + } + + """ + :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. If a start and end range is provided, the date will be converted to its UTC equivalent with the ranges as reference and stored in UTC. 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. The time will be stored and returned as UTC standard timezone. + :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. The time will be stored and returned as UTC standard timezone. + :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 order_cancellation_reason: If the order is cancelled this field will provide further context on the cause of the cancellation. + :ivar losing_carrier_information: + :ivar phone_numbers: + :ivar bundle_sid: The bundle sid is an optional identifier to reference a group of regulatory documents for a port request. + :ivar portability_advance_carrier: A field only required for Japan port in requests. It is a unique identifier for the donor carrier service the line is being ported from. + :ivar auto_cancel_approval_numbers: Japan specific field, indicates the number of phone numbers to automatically approve for cancellation. + :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: + :ivar support_ticket_id: Unique ID of the request's support ticket + :ivar signature_request_url: + """ + + 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.order_cancellation_reason: Optional[str] = payload.get( + "order_cancellation_reason" + ) + self.losing_carrier_information: Optional[str] = payload.get( + "losing_carrier_information" + ) + self.phone_numbers: Optional[List[str]] = payload.get("phone_numbers") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.portability_advance_carrier: Optional[str] = payload.get( + "portability_advance_carrier" + ) + self.auto_cancel_approval_numbers: Optional[str] = payload.get( + "auto_cancel_approval_numbers" + ) + self.documents: Optional[List[str]] = payload.get("documents") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.support_ticket_id: Optional[int] = deserialize.integer( + payload.get("support_ticket_id") + ) + self.signature_request_url: Optional[str] = payload.get("signature_request_url") + + 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PortingPortInInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PortingPortInInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PortingPortInInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PortingPortInInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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): + + class NumbersV1PortingAddress(object): + """ + :ivar street: The street address, ex: 101 Spear St + :ivar street_2: The building information, ex : 5th floor. + :ivar city: The city name, ex: San Francisco. + :ivar state: The state name, ex: CA or California. Note this should match the losing carrier’s information exactly. So if they spell out the entire state’s name instead of abbreviating it, please do so. + :ivar zip: The zip code, ex: 94105. + :ivar country: The country, ex: USA. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.street: Optional[str] = payload.get("street") + self.street_2: Optional[str] = payload.get("street_2") + self.city: Optional[str] = payload.get("city") + self.state: Optional[str] = payload.get("state") + self.zip: Optional[str] = payload.get("zip") + self.country: Optional[str] = payload.get("country") + + def to_dict(self): + return { + "street": self.street, + "street_2": self.street_2, + "city": self.city, + "state": self.state, + "zip": self.zip, + "country": self.country, + } + + class NumbersV1PortingLosingCarrierInformation(object): + """ + :ivar customer_name: Customer name as it is registered with the losing carrier. This can be an individual or a business name depending on the customer type selected. + :ivar account_number: The account number of the customer for the losing carrier. Only require for mobile phone numbers. + :ivar account_telephone_number: The account phone number of the customer for the losing carrier. + :ivar address_sid: If you already have an Address SID that represents the address needed for the LOA, you can provide an Address SID instead of providing the address object in the request body. This will copy the address into the port in request. If changes are made to the Address SID after port in request creation, those changes will not be reflected in the port in request. + :ivar address: + :ivar authorized_representative: The first and last name of the person listed with the losing carrier who is authorized to make changes on the account. + :ivar authorized_representative_email: Email address of the person (owner of the number) who will sign the letter of authorization for the port in request. This email address should belong to the person named in as the authorized representative. + :ivar customer_type: The type of customer account in the losing carrier. This should either be: 'Individual' or 'Business'. + :ivar authorized_representative_katakana: + :ivar sub_municipality: + :ivar building: + :ivar katakana_name: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_name: Optional[str] = payload.get("customer_name") + self.account_number: Optional[str] = payload.get("account_number") + self.account_telephone_number: Optional[str] = payload.get( + "account_telephone_number" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.address: Optional[PortingPortInList.NumbersV1PortingAddress] = ( + payload.get("address") + ) + self.authorized_representative: Optional[str] = payload.get( + "authorized_representative" + ) + self.authorized_representative_email: Optional[str] = payload.get( + "authorized_representative_email" + ) + self.customer_type: Optional["PortingPortInInstance.str"] = payload.get( + "customer_type" + ) + self.authorized_representative_katakana: Optional[str] = payload.get( + "authorized_representative_katakana" + ) + self.sub_municipality: Optional[str] = payload.get("sub_municipality") + self.building: Optional[str] = payload.get("building") + self.katakana_name: Optional[str] = payload.get("katakana_name") + + def to_dict(self): + return { + "customer_name": self.customer_name, + "account_number": self.account_number, + "account_telephone_number": self.account_telephone_number, + "address_sid": self.address_sid, + "address": self.address.to_dict() if self.address is not None else None, + "authorized_representative": self.authorized_representative, + "authorized_representative_email": self.authorized_representative_email, + "customer_type": self.customer_type, + "authorized_representative_katakana": self.authorized_representative_katakana, + "sub_municipality": self.sub_municipality, + "building": self.building, + "katakana_name": self.katakana_name, + } + + class NumbersV1PortingPortInCreate(object): + """ + :ivar account_sid: Account Sid or subaccount where the phone number(s) will be Ported + :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 phone_numbers: List of phone numbers to be ported. Maximum of 1,000 phone numbers per request. + :ivar losing_carrier_information: + :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 bundle_sid: The bundle sid is an optional identifier to reference a group of regulatory documents for a port request. + :ivar portability_advance_carrier: A field only required for Japan port in requests. It is a unique identifier for the donor carrier service the line is being ported from. + :ivar auto_cancel_approval_numbers: Japan specific field, indicates the number of phone numbers to automatically approve for cancellation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.account_sid: Optional[str] = payload.get("account_sid") + self.documents: Optional[List[str]] = payload.get("documents") + self.phone_numbers: Optional[ + List[PortingPortInList.NumbersV1PortingPortInCreatePhoneNumbers] + ] = payload.get("phone_numbers") + self.losing_carrier_information: Optional[ + PortingPortInList.NumbersV1PortingLosingCarrierInformation + ] = payload.get("losing_carrier_information") + self.notification_emails: Optional[List[str]] = payload.get( + "notification_emails" + ) + self.target_port_in_date: Optional[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.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.portability_advance_carrier: Optional[str] = payload.get( + "portability_advance_carrier" + ) + self.auto_cancel_approval_numbers: Optional[str] = payload.get( + "auto_cancel_approval_numbers" + ) + + def to_dict(self): + return { + "account_sid": self.account_sid, + "documents": self.documents, + "phone_numbers": ( + [phone_numbers.to_dict() for phone_numbers in self.phone_numbers] + if self.phone_numbers is not None + else None + ), + "losing_carrier_information": ( + self.losing_carrier_information.to_dict() + if self.losing_carrier_information is not None + else None + ), + "notification_emails": self.notification_emails, + "target_port_in_date": self.target_port_in_date, + "target_port_in_time_range_start": self.target_port_in_time_range_start, + "target_port_in_time_range_end": self.target_port_in_time_range_end, + "bundle_sid": self.bundle_sid, + "portability_advance_carrier": self.portability_advance_carrier, + "auto_cancel_approval_numbers": self.auto_cancel_approval_numbers, + } + + class NumbersV1PortingPortInCreatePhoneNumbers(object): + """ + :ivar phone_number: Phone number to be ported. This must be in the E164 Format. + :ivar pin: Some losing carriers require a PIN to authorize the port of a phone number. If the phone number is a US mobile phone number, the PIN is mandatory to process a porting request. Other carriers and number types may also require a PIN, you'll need to contact the losing carrier to determine what your phone number's PIN is. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_number: Optional[str] = payload.get("phone_number") + self.pin: Optional[str] = payload.get("pin") + + def to_dict(self): + return { + "phone_number": self.phone_number, + "pin": self.pin, + } + + 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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the PortingPortInInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PortingPortInInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PortingPortInInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PortingPortInInstance: + """ + Fetch the PortingPortInInstance + + + :returns: The fetched PortingPortInInstance + """ + payload, _, _ = self._fetch() + return PortingPortInInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PortingPortInInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PortingPortInInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> PortingPortInInstance: + """ + Asynchronous coroutine to fetch the PortingPortInInstance + + + :returns: The fetched PortingPortInInstance + """ + payload, _, _ = await self._fetch_async() + return PortingPortInInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PortingPortInInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PortingPortInInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 PortingPortInList(ListResource): + + class NumbersV1PortingAddress(object): + """ + :ivar street: The street address, ex: 101 Spear St + :ivar street_2: The building information, ex : 5th floor. + :ivar city: The city name, ex: San Francisco. + :ivar state: The state name, ex: CA or California. Note this should match the losing carrier’s information exactly. So if they spell out the entire state’s name instead of abbreviating it, please do so. + :ivar zip: The zip code, ex: 94105. + :ivar country: The country, ex: USA. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.street: Optional[str] = payload.get("street") + self.street_2: Optional[str] = payload.get("street_2") + self.city: Optional[str] = payload.get("city") + self.state: Optional[str] = payload.get("state") + self.zip: Optional[str] = payload.get("zip") + self.country: Optional[str] = payload.get("country") + + def to_dict(self): + return { + "street": self.street, + "street_2": self.street_2, + "city": self.city, + "state": self.state, + "zip": self.zip, + "country": self.country, + } + + class NumbersV1PortingLosingCarrierInformation(object): + """ + :ivar customer_name: Customer name as it is registered with the losing carrier. This can be an individual or a business name depending on the customer type selected. + :ivar account_number: The account number of the customer for the losing carrier. Only require for mobile phone numbers. + :ivar account_telephone_number: The account phone number of the customer for the losing carrier. + :ivar address_sid: If you already have an Address SID that represents the address needed for the LOA, you can provide an Address SID instead of providing the address object in the request body. This will copy the address into the port in request. If changes are made to the Address SID after port in request creation, those changes will not be reflected in the port in request. + :ivar address: + :ivar authorized_representative: The first and last name of the person listed with the losing carrier who is authorized to make changes on the account. + :ivar authorized_representative_email: Email address of the person (owner of the number) who will sign the letter of authorization for the port in request. This email address should belong to the person named in as the authorized representative. + :ivar customer_type: The type of customer account in the losing carrier. This should either be: 'Individual' or 'Business'. + :ivar authorized_representative_katakana: + :ivar sub_municipality: + :ivar building: + :ivar katakana_name: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_name: Optional[str] = payload.get("customer_name") + self.account_number: Optional[str] = payload.get("account_number") + self.account_telephone_number: Optional[str] = payload.get( + "account_telephone_number" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.address: Optional[PortingPortInList.NumbersV1PortingAddress] = ( + payload.get("address") + ) + self.authorized_representative: Optional[str] = payload.get( + "authorized_representative" + ) + self.authorized_representative_email: Optional[str] = payload.get( + "authorized_representative_email" + ) + self.customer_type: Optional["PortingPortInInstance.str"] = payload.get( + "customer_type" + ) + self.authorized_representative_katakana: Optional[str] = payload.get( + "authorized_representative_katakana" + ) + self.sub_municipality: Optional[str] = payload.get("sub_municipality") + self.building: Optional[str] = payload.get("building") + self.katakana_name: Optional[str] = payload.get("katakana_name") + + def to_dict(self): + return { + "customer_name": self.customer_name, + "account_number": self.account_number, + "account_telephone_number": self.account_telephone_number, + "address_sid": self.address_sid, + "address": self.address.to_dict() if self.address is not None else None, + "authorized_representative": self.authorized_representative, + "authorized_representative_email": self.authorized_representative_email, + "customer_type": self.customer_type, + "authorized_representative_katakana": self.authorized_representative_katakana, + "sub_municipality": self.sub_municipality, + "building": self.building, + "katakana_name": self.katakana_name, + } + + class NumbersV1PortingPortInCreate(object): + """ + :ivar account_sid: Account Sid or subaccount where the phone number(s) will be Ported + :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 phone_numbers: List of phone numbers to be ported. Maximum of 1,000 phone numbers per request. + :ivar losing_carrier_information: + :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 bundle_sid: The bundle sid is an optional identifier to reference a group of regulatory documents for a port request. + :ivar portability_advance_carrier: A field only required for Japan port in requests. It is a unique identifier for the donor carrier service the line is being ported from. + :ivar auto_cancel_approval_numbers: Japan specific field, indicates the number of phone numbers to automatically approve for cancellation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.account_sid: Optional[str] = payload.get("account_sid") + self.documents: Optional[List[str]] = payload.get("documents") + self.phone_numbers: Optional[ + List[PortingPortInList.NumbersV1PortingPortInCreatePhoneNumbers] + ] = payload.get("phone_numbers") + self.losing_carrier_information: Optional[ + PortingPortInList.NumbersV1PortingLosingCarrierInformation + ] = payload.get("losing_carrier_information") + self.notification_emails: Optional[List[str]] = payload.get( + "notification_emails" + ) + self.target_port_in_date: Optional[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.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.portability_advance_carrier: Optional[str] = payload.get( + "portability_advance_carrier" + ) + self.auto_cancel_approval_numbers: Optional[str] = payload.get( + "auto_cancel_approval_numbers" + ) + + def to_dict(self): + return { + "account_sid": self.account_sid, + "documents": self.documents, + "phone_numbers": ( + [phone_numbers.to_dict() for phone_numbers in self.phone_numbers] + if self.phone_numbers is not None + else None + ), + "losing_carrier_information": ( + self.losing_carrier_information.to_dict() + if self.losing_carrier_information is not None + else None + ), + "notification_emails": self.notification_emails, + "target_port_in_date": self.target_port_in_date, + "target_port_in_time_range_start": self.target_port_in_time_range_start, + "target_port_in_time_range_end": self.target_port_in_time_range_end, + "bundle_sid": self.bundle_sid, + "portability_advance_carrier": self.portability_advance_carrier, + "auto_cancel_approval_numbers": self.auto_cancel_approval_numbers, + } + + class NumbersV1PortingPortInCreatePhoneNumbers(object): + """ + :ivar phone_number: Phone number to be ported. This must be in the E164 Format. + :ivar pin: Some losing carriers require a PIN to authorize the port of a phone number. If the phone number is a US mobile phone number, the PIN is mandatory to process a porting request. Other carriers and number types may also require a PIN, you'll need to contact the losing carrier to determine what your phone number's PIN is. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_number: Optional[str] = payload.get("phone_number") + self.pin: Optional[str] = payload.get("pin") + + def to_dict(self): + return { + "phone_number": self.phone_number, + "pin": self.pin, + } + + 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, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = numbers_v1_porting_port_in_create.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> PortingPortInInstance: + """ + Create the PortingPortInInstance + + :param numbers_v1_porting_port_in_create: + + :returns: The created PortingPortInInstance + """ + payload, _, _ = self._create( + numbers_v1_porting_port_in_create=numbers_v1_porting_port_in_create + ) + return PortingPortInInstance(self._version, payload) + + def create_with_http_info( + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> ApiResponse: + """ + Create the PortingPortInInstance and return response metadata + + :param numbers_v1_porting_port_in_create: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + numbers_v1_porting_port_in_create=numbers_v1_porting_port_in_create + ) + instance = PortingPortInInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = numbers_v1_porting_port_in_create.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> PortingPortInInstance: + """ + Asynchronously create the PortingPortInInstance + + :param numbers_v1_porting_port_in_create: + + :returns: The created PortingPortInInstance + """ + payload, _, _ = await self._create_async( + numbers_v1_porting_port_in_create=numbers_v1_porting_port_in_create + ) + return PortingPortInInstance(self._version, payload) + + async def create_with_http_info_async( + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> ApiResponse: + """ + Asynchronously create the PortingPortInInstance and return response metadata + + :param numbers_v1_porting_port_in_create: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + numbers_v1_porting_port_in_create=numbers_v1_porting_port_in_create + ) + instance = PortingPortInInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..1efa19ebe8 --- /dev/null +++ b/twilio/rest/numbers/v1/porting_port_in_phone_number.py @@ -0,0 +1,440 @@ +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.api_response import ApiResponse +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PortingPortInPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PortingPortInPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PortingPortInPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PortingPortInPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the PortingPortInPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PortingPortInPhoneNumberInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PortingPortInPhoneNumberInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PortingPortInPhoneNumberInstance: + """ + Fetch the PortingPortInPhoneNumberInstance + + + :returns: The fetched PortingPortInPhoneNumberInstance + """ + payload, _, _ = self._fetch() + return PortingPortInPhoneNumberInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + phone_number_sid=self._solution["phone_number_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PortingPortInPhoneNumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PortingPortInPhoneNumberInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + phone_number_sid=self._solution["phone_number_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> PortingPortInPhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PortingPortInPhoneNumberInstance + + + :returns: The fetched PortingPortInPhoneNumberInstance + """ + payload, _, _ = await self._fetch_async() + 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PortingPortInPhoneNumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PortingPortInPhoneNumberInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + phone_number_sid=self._solution["phone_number_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..5bcc0e604c --- /dev/null +++ b/twilio/rest/numbers/v1/porting_portability.py @@ -0,0 +1,377 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the PortingPortabilityInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + target_account_sid=target_account_sid, + address_sid=address_sid, + ) + + async def fetch_with_http_info_async( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PortingPortabilityInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "TargetAccountSid": target_account_sid, + "AddressSid": address_sid, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = self._fetch( + target_account_sid=target_account_sid, address_sid=address_sid + ) + return PortingPortabilityInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + def fetch_with_http_info( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the PortingPortabilityInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + target_account_sid=target_account_sid, address_sid=address_sid + ) + instance = PortingPortabilityInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "TargetAccountSid": target_account_sid, + "AddressSid": address_sid, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async( + target_account_sid=target_account_sid, address_sid=address_sid + ) + return PortingPortabilityInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_with_http_info_async( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PortingPortabilityInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + target_account_sid=target_account_sid, address_sid=address_sid + ) + instance = PortingPortabilityInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..4769c6ae74 --- /dev/null +++ b/twilio/rest/numbers/v1/porting_webhook_configuration.py @@ -0,0 +1,161 @@ +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.api_response import ApiResponse + +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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, body: Union[object, object] = values.unset + ) -> PortingWebhookConfigurationInstance: + """ + Create the PortingWebhookConfigurationInstance + + :param body: + + :returns: The created PortingWebhookConfigurationInstance + """ + payload, _, _ = self._create(body=body) + return PortingWebhookConfigurationInstance(self._version, payload) + + def create_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the PortingWebhookConfigurationInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body) + instance = PortingWebhookConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> PortingWebhookConfigurationInstance: + """ + Asynchronously create the PortingWebhookConfigurationInstance + + :param body: + + :returns: The created PortingWebhookConfigurationInstance + """ + payload, _, _ = await self._create_async(body=body) + return PortingWebhookConfigurationInstance(self._version, payload) + + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the PortingWebhookConfigurationInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(body=body) + instance = PortingWebhookConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..e724498b0a --- /dev/null +++ b/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py @@ -0,0 +1,167 @@ +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.api_response import ApiResponse +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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the PortingWebhookConfigurationDeleteInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PortingWebhookConfigurationDeleteInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PortingWebhookConfigurationDeleteInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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/sender_id_registration.py b/twilio/rest/numbers/v1/sender_id_registration.py new file mode 100644 index 0000000000..6995e6a84e --- /dev/null +++ b/twilio/rest/numbers/v1/sender_id_registration.py @@ -0,0 +1,279 @@ +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.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SenderIdRegistrationInstance(InstanceResource): + + class NumbersV1CreateEmbeddedRegistrationRequest(object): + """ + :ivar regulation_id: The regulation for this registration. + :ivar regulation_version: The regulation version. + :ivar friendly_name: Human-readable name for the registration. + :ivar status_notification_email: Email address for registration status notifications. + :ivar status_callback_url: The URL of this resource. + :ivar comments: Additional comments about the registration. + :ivar theme_set_id: Theme ID for the Compliance Embeddable UI. + :ivar data: Registration data organized by section (alphanumericSender, business, useCase, authorizedRepresentative, officer, businessAddress). + """ + + def __init__(self, payload: Dict[str, Any]): + + self.regulation_id: Optional[str] = payload.get("regulationId") + self.regulation_version: Optional[int] = payload.get("regulationVersion") + self.friendly_name: Optional[str] = payload.get("friendlyName") + self.status_notification_email: Optional[str] = payload.get( + "statusNotificationEmail" + ) + self.status_callback_url: Optional[str] = payload.get("statusCallbackUrl") + self.comments: Optional[str] = payload.get("comments") + self.theme_set_id: Optional[str] = payload.get("themeSetId") + self.data: Optional[Dict[str, object]] = payload.get("data") + + def to_dict(self): + return { + "regulationId": self.regulation_id, + "regulationVersion": self.regulation_version, + "friendlyName": self.friendly_name, + "statusNotificationEmail": self.status_notification_email, + "statusCallbackUrl": self.status_callback_url, + "comments": self.comments, + "themeSetId": self.theme_set_id, + "data": self.data, + } + + """ + :ivar id: Registration identifier (BU-prefixed). + :ivar regulation_id: The regulation ID for this registration. + :ivar regulation_version: The regulation version. + :ivar friendly_name: The friendly name provided in the request. + :ivar status: Registration status. Always DRAFT on creation. + :ivar status_notification_email: Email address for status notifications. + :ivar status_callback_url: Callback URL for status webhooks. + :ivar comments: Additional comments. + :ivar embedded_session: + :ivar data: Registration data echoed from the request. + :ivar date_created: Timestamp of creation. + :ivar date_updated: Timestamp of last update. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.regulation_id: Optional[str] = payload.get("regulationId") + self.regulation_version: Optional[int] = deserialize.integer( + payload.get("regulationVersion") + ) + self.friendly_name: Optional[str] = payload.get("friendlyName") + self.status: Optional[str] = payload.get("status") + self.status_notification_email: Optional[str] = payload.get( + "statusNotificationEmail" + ) + self.status_callback_url: Optional[str] = payload.get("statusCallbackUrl") + self.comments: Optional[str] = payload.get("comments") + self.embedded_session: Optional[str] = payload.get("embeddedSession") + self.data: Optional[Dict[str, object]] = payload.get("data") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateCreated") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateUpdated") + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class SenderIdRegistrationList(ListResource): + + class NumbersV1CreateEmbeddedRegistrationRequest(object): + """ + :ivar regulation_id: The regulation for this registration. + :ivar regulation_version: The regulation version. + :ivar friendly_name: Human-readable name for the registration. + :ivar status_notification_email: Email address for registration status notifications. + :ivar status_callback_url: The URL of this resource. + :ivar comments: Additional comments about the registration. + :ivar theme_set_id: Theme ID for the Compliance Embeddable UI. + :ivar data: Registration data organized by section (alphanumericSender, business, useCase, authorizedRepresentative, officer, businessAddress). + """ + + def __init__(self, payload: Dict[str, Any]): + + self.regulation_id: Optional[str] = payload.get("regulationId") + self.regulation_version: Optional[int] = payload.get("regulationVersion") + self.friendly_name: Optional[str] = payload.get("friendlyName") + self.status_notification_email: Optional[str] = payload.get( + "statusNotificationEmail" + ) + self.status_callback_url: Optional[str] = payload.get("statusCallbackUrl") + self.comments: Optional[str] = payload.get("comments") + self.theme_set_id: Optional[str] = payload.get("themeSetId") + self.data: Optional[Dict[str, object]] = payload.get("data") + + def to_dict(self): + return { + "regulationId": self.regulation_id, + "regulationVersion": self.regulation_version, + "friendlyName": self.friendly_name, + "statusNotificationEmail": self.status_notification_email, + "statusCallbackUrl": self.status_callback_url, + "comments": self.comments, + "themeSetId": self.theme_set_id, + "data": self.data, + } + + def __init__(self, version: Version): + """ + Initialize the SenderIdRegistrationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SenderIdRegistrations" + + def _create( + self, + numbers_v1_create_embedded_registration_request: NumbersV1CreateEmbeddedRegistrationRequest, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = numbers_v1_create_embedded_registration_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + numbers_v1_create_embedded_registration_request: NumbersV1CreateEmbeddedRegistrationRequest, + ) -> SenderIdRegistrationInstance: + """ + Create the SenderIdRegistrationInstance + + :param numbers_v1_create_embedded_registration_request: + + :returns: The created SenderIdRegistrationInstance + """ + payload, _, _ = self._create( + numbers_v1_create_embedded_registration_request=numbers_v1_create_embedded_registration_request + ) + return SenderIdRegistrationInstance(self._version, payload) + + def create_with_http_info( + self, + numbers_v1_create_embedded_registration_request: NumbersV1CreateEmbeddedRegistrationRequest, + ) -> ApiResponse: + """ + Create the SenderIdRegistrationInstance and return response metadata + + :param numbers_v1_create_embedded_registration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + numbers_v1_create_embedded_registration_request=numbers_v1_create_embedded_registration_request + ) + instance = SenderIdRegistrationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + numbers_v1_create_embedded_registration_request: NumbersV1CreateEmbeddedRegistrationRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = numbers_v1_create_embedded_registration_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + numbers_v1_create_embedded_registration_request: NumbersV1CreateEmbeddedRegistrationRequest, + ) -> SenderIdRegistrationInstance: + """ + Asynchronously create the SenderIdRegistrationInstance + + :param numbers_v1_create_embedded_registration_request: + + :returns: The created SenderIdRegistrationInstance + """ + payload, _, _ = await self._create_async( + numbers_v1_create_embedded_registration_request=numbers_v1_create_embedded_registration_request + ) + return SenderIdRegistrationInstance(self._version, payload) + + async def create_with_http_info_async( + self, + numbers_v1_create_embedded_registration_request: NumbersV1CreateEmbeddedRegistrationRequest, + ) -> ApiResponse: + """ + Asynchronously create the SenderIdRegistrationInstance and return response metadata + + :param numbers_v1_create_embedded_registration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + numbers_v1_create_embedded_registration_request=numbers_v1_create_embedded_registration_request + ) + instance = SenderIdRegistrationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..18e6f97003 --- /dev/null +++ b/twilio/rest/numbers/v1/signing_request_configuration.py @@ -0,0 +1,627 @@ +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.api_response import ApiResponse + +from twilio.base.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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, body: Union[object, object] = values.unset + ) -> SigningRequestConfigurationInstance: + """ + Create the SigningRequestConfigurationInstance + + :param body: + + :returns: The created SigningRequestConfigurationInstance + """ + payload, _, _ = self._create(body=body) + return SigningRequestConfigurationInstance(self._version, payload) + + def create_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the SigningRequestConfigurationInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body) + instance = SigningRequestConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> SigningRequestConfigurationInstance: + """ + Asynchronously create the SigningRequestConfigurationInstance + + :param body: + + :returns: The created SigningRequestConfigurationInstance + """ + payload, _, _ = await self._create_async(body=body) + return SigningRequestConfigurationInstance(self._version, payload) + + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the SigningRequestConfigurationInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(body=body) + instance = SigningRequestConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SigningRequestConfigurationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + country=country, product=product, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SigningRequestConfigurationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + country=country, product=product, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SigningRequestConfigurationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + country=country, + product=product, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SigningRequestConfigurationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + country=country, + product=product, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with SigningRequestConfigurationPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SigningRequestConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with SigningRequestConfigurationPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SigningRequestConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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/v1/webhook.py b/twilio/rest/numbers/v1/webhook.py new file mode 100644 index 0000000000..c5c9783f7f --- /dev/null +++ b/twilio/rest/numbers/v1/webhook.py @@ -0,0 +1,150 @@ +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.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WebhookInstance(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 WebhookList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Porting/Configuration/Webhook" + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = self._fetch() + return WebhookInstance(self._version, payload) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronously fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() + return WebhookInstance(self._version, payload) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..e4f3060250 100644 --- a/twilio/rest/numbers/v2/__init__.py +++ b/twilio/rest/numbers/v2/__init__.py @@ -1,42 +1,83 @@ -# 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.application import ApplicationList +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._applications: Optional[ApplicationList] = None + 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 applications(self) -> ApplicationList: + if self._applications is None: + self._applications = ApplicationList(self) + return self._applications + + @property + def authorization_documents(self) -> AuthorizationDocumentList: + if self._authorization_documents is None: + self._authorization_documents = AuthorizationDocumentList(self) + return self._authorization_documents + + @property + def bulk_hosted_number_orders(self) -> BulkHostedNumberOrderList: + if self._bulk_hosted_number_orders is None: + self._bulk_hosted_number_orders = BulkHostedNumberOrderList(self) + return self._bulk_hosted_number_orders + + @property + def bundle_clone(self) -> BundleCloneList: + if self._bundle_clone is None: + self._bundle_clone = BundleCloneList(self) + return self._bundle_clone + + @property + def hosted_number_orders(self) -> HostedNumberOrderList: + if self._hosted_number_orders is None: + self._hosted_number_orders = HostedNumberOrderList(self) + return self._hosted_number_orders + + @property + def regulatory_compliance(self) -> RegulatoryComplianceList: if self._regulatory_compliance is None: self._regulatory_compliance = RegulatoryComplianceList(self) return self._regulatory_compliance - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/numbers/v2/application.py b/twilio/rest/numbers/v2/application.py new file mode 100644 index 0000000000..1381c1d7a2 --- /dev/null +++ b/twilio/rest/numbers/v2/application.py @@ -0,0 +1,1166 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ApplicationInstance(InstanceResource): + + class CreateShortCodeApplicationRequest(object): + """ + :ivar friendly_name: The friendly name for the short code application. + :ivar iso_country: The ISO country code. + :ivar business_information: + :ivar setup: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iso_country: Optional[str] = payload.get("iso_country") + self.business_information: Optional[ + ApplicationList.CreateShortCodeApplicationRequestBusinessInformation + ] = payload.get("business_information") + self.setup: Optional[ + ApplicationList.CreateShortCodeApplicationRequestSetup + ] = payload.get("setup") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "iso_country": self.iso_country, + "business_information": ( + self.business_information.to_dict() + if self.business_information is not None + else None + ), + "setup": self.setup.to_dict() if self.setup is not None else None, + } + + class CreateShortCodeApplicationRequestBusinessInformation(object): + """ + :ivar customer_facing_profile: The Compliance Profile SID for the customer-facing business profile. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_facing_profile: Optional[str] = payload.get( + "customer_facing_profile" + ) + + def to_dict(self): + return { + "customer_facing_profile": self.customer_facing_profile, + } + + class CreateShortCodeApplicationRequestSetup(object): + """ + :ivar charges_apply: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.charges_apply: Optional[bool] = payload.get("charges_apply") + + def to_dict(self): + return { + "charges_apply": self.charges_apply, + } + + """ + :ivar sid: The unique identifier of the Short Code Application. + :ivar application_requirements_sid: The Application Requirements SID. + :ivar application_requirements_version: The version of the application requirements. + :ivar account_sid: The Account SID associated with the application. + :ivar bundle_sid: The Bundle SID for regulatory compliance. + :ivar reviewer: The reviewer of the application. + :ivar zendesk_ticket_id: The Zendesk ticket ID associated with the application. + :ivar friendly_name: The friendly name of the application. + :ivar notification_emails: The notification emails for the application. + :ivar iso_country: The ISO country code. + :ivar state: The state of the application. + :ivar setup: + :ivar business_information: + :ivar user_sign_up: + :ivar compliance_keywords: + :ivar content_examples: + :ivar sms_campaign_details: + :ivar date_created: The date and time the application was created. + :ivar date_updated: The date and time the application was last updated. + :ivar created_by: The identity of the user who created the application. + :ivar updated_by: The identity of the user who last updated the application. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.application_requirements_sid: Optional[str] = payload.get( + "application_requirements_sid" + ) + self.application_requirements_version: Optional[int] = deserialize.integer( + payload.get("application_requirements_version") + ) + self.account_sid: Optional[str] = payload.get("account_sid") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.reviewer: Optional[str] = payload.get("reviewer") + self.zendesk_ticket_id: Optional[str] = payload.get("zendesk_ticket_id") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.notification_emails: Optional[List[str]] = payload.get( + "notification_emails" + ) + self.iso_country: Optional[str] = payload.get("iso_country") + self.state: Optional["ApplicationInstance.str"] = payload.get("state") + self.setup: Optional[str] = payload.get("setup") + self.business_information: Optional[str] = payload.get("business_information") + self.user_sign_up: Optional[str] = payload.get("user_sign_up") + self.compliance_keywords: Optional[str] = payload.get("compliance_keywords") + self.content_examples: Optional[str] = payload.get("content_examples") + self.sms_campaign_details: Optional[str] = payload.get("sms_campaign_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") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.updated_by: Optional[str] = payload.get("updated_by") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[ApplicationContext] = None + + @property + def _proxy(self) -> "ApplicationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ApplicationContext for this ApplicationInstance + """ + if self._context is None: + self._context = ApplicationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ApplicationInstance": + """ + Fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ApplicationInstance": + """ + Asynchronous coroutine to fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ApplicationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApplicationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 ApplicationContext(InstanceContext): + + class CreateShortCodeApplicationRequest(object): + """ + :ivar friendly_name: The friendly name for the short code application. + :ivar iso_country: The ISO country code. + :ivar business_information: + :ivar setup: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iso_country: Optional[str] = payload.get("iso_country") + self.business_information: Optional[ + ApplicationList.CreateShortCodeApplicationRequestBusinessInformation + ] = payload.get("business_information") + self.setup: Optional[ + ApplicationList.CreateShortCodeApplicationRequestSetup + ] = payload.get("setup") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "iso_country": self.iso_country, + "business_information": ( + self.business_information.to_dict() + if self.business_information is not None + else None + ), + "setup": self.setup.to_dict() if self.setup is not None else None, + } + + class CreateShortCodeApplicationRequestBusinessInformation(object): + """ + :ivar customer_facing_profile: The Compliance Profile SID for the customer-facing business profile. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_facing_profile: Optional[str] = payload.get( + "customer_facing_profile" + ) + + def to_dict(self): + return { + "customer_facing_profile": self.customer_facing_profile, + } + + class CreateShortCodeApplicationRequestSetup(object): + """ + :ivar charges_apply: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.charges_apply: Optional[bool] = payload.get("charges_apply") + + def to_dict(self): + return { + "charges_apply": self.charges_apply, + } + + def __init__(self, version: Version, sid: str): + """ + Initialize the ApplicationContext + + :param version: Version that contains the resource + :param sid: The unique string that identifies the Short Code Application resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/ShortCodes/Applications/{sid}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ApplicationInstance: + """ + Fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + payload, _, _ = self._fetch() + return ApplicationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ApplicationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ApplicationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ApplicationInstance: + """ + Asynchronous coroutine to fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + payload, _, _ = await self._fetch_async() + return ApplicationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApplicationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ApplicationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 ApplicationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ApplicationInstance: + """ + Build an instance of ApplicationInstance + + :param payload: Payload response from the API + """ + + return ApplicationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ApplicationList(ListResource): + + class CreateShortCodeApplicationRequest(object): + """ + :ivar friendly_name: The friendly name for the short code application. + :ivar iso_country: The ISO country code. + :ivar business_information: + :ivar setup: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iso_country: Optional[str] = payload.get("iso_country") + self.business_information: Optional[ + ApplicationList.CreateShortCodeApplicationRequestBusinessInformation + ] = payload.get("business_information") + self.setup: Optional[ + ApplicationList.CreateShortCodeApplicationRequestSetup + ] = payload.get("setup") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "iso_country": self.iso_country, + "business_information": ( + self.business_information.to_dict() + if self.business_information is not None + else None + ), + "setup": self.setup.to_dict() if self.setup is not None else None, + } + + class CreateShortCodeApplicationRequestBusinessInformation(object): + """ + :ivar customer_facing_profile: The Compliance Profile SID for the customer-facing business profile. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_facing_profile: Optional[str] = payload.get( + "customer_facing_profile" + ) + + def to_dict(self): + return { + "customer_facing_profile": self.customer_facing_profile, + } + + class CreateShortCodeApplicationRequestSetup(object): + """ + :ivar charges_apply: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.charges_apply: Optional[bool] = payload.get("charges_apply") + + def to_dict(self): + return { + "charges_apply": self.charges_apply, + } + + def __init__(self, version: Version): + """ + Initialize the ApplicationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ShortCodes/Applications" + + def _create( + self, create_short_code_application_request: CreateShortCodeApplicationRequest + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_short_code_application_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_short_code_application_request: CreateShortCodeApplicationRequest + ) -> ApplicationInstance: + """ + Create the ApplicationInstance + + :param create_short_code_application_request: + + :returns: The created ApplicationInstance + """ + payload, _, _ = self._create( + create_short_code_application_request=create_short_code_application_request + ) + return ApplicationInstance(self._version, payload) + + def create_with_http_info( + self, create_short_code_application_request: CreateShortCodeApplicationRequest + ) -> ApiResponse: + """ + Create the ApplicationInstance and return response metadata + + :param create_short_code_application_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_short_code_application_request=create_short_code_application_request + ) + instance = ApplicationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_short_code_application_request: CreateShortCodeApplicationRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_short_code_application_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_short_code_application_request: CreateShortCodeApplicationRequest + ) -> ApplicationInstance: + """ + Asynchronously create the ApplicationInstance + + :param create_short_code_application_request: + + :returns: The created ApplicationInstance + """ + payload, _, _ = await self._create_async( + create_short_code_application_request=create_short_code_application_request + ) + return ApplicationInstance(self._version, payload) + + async def create_with_http_info_async( + self, create_short_code_application_request: CreateShortCodeApplicationRequest + ) -> ApiResponse: + """ + Asynchronously create the ApplicationInstance and return response metadata + + :param create_short_code_application_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_short_code_application_request=create_short_code_application_request + ) + instance = ApplicationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ApplicationInstance]: + """ + Streams ApplicationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter 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( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=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, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ApplicationInstance]: + """ + Asynchronously streams ApplicationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter 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( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ApplicationInstance and returns headers from first page + + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ApplicationInstance and returns headers from first page + + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ApplicationInstance]: + """ + Lists ApplicationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter 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( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ApplicationInstance]: + """ + Asynchronously lists ApplicationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter 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( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=sid, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ApplicationInstance and returns headers from first page + + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ApplicationInstance and returns headers from first page + + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: 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, + ) -> ApplicationPage: + """ + Retrieve a single page of ApplicationInstance records from the API. + Request is executed immediately + + :param account_sid: The Account SID to filter by. + :param iso_country: The ISO country to filter by. + :param status: The application status to filter by. + :param friendly_name: The friendly name to filter by. + :param sid: The application SID to filter 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 ApplicationInstance + """ + data = values.of( + { + "AccountSid": account_sid, + "IsoCountry": iso_country, + "Status": status, + "FriendlyName": friendly_name, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ApplicationPage(self._version, response) + + async def page_async( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: 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, + ) -> ApplicationPage: + """ + Asynchronously retrieve a single page of ApplicationInstance records from the API. + Request is executed immediately + + :param account_sid: The Account SID to filter by. + :param iso_country: The ISO country to filter by. + :param status: The application status to filter by. + :param friendly_name: The friendly name to filter by. + :param sid: The application SID to filter 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 ApplicationInstance + """ + data = values.of( + { + "AccountSid": account_sid, + "IsoCountry": iso_country, + "Status": status, + "FriendlyName": friendly_name, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ApplicationPage(self._version, response) + + def page_with_http_info( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param account_sid: The Account SID to filter by. + :param iso_country: The ISO country to filter by. + :param status: The application status to filter by. + :param friendly_name: The friendly name to filter by. + :param sid: The application SID to filter 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: ApiResponse with ApplicationPage, status code, and headers + """ + data = values.of( + { + "AccountSid": account_sid, + "IsoCountry": iso_country, + "Status": status, + "FriendlyName": friendly_name, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ApplicationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: 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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param account_sid: The Account SID to filter by. + :param iso_country: The ISO country to filter by. + :param status: The application status to filter by. + :param friendly_name: The friendly name to filter by. + :param sid: The application SID to filter 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: ApiResponse with ApplicationPage, status code, and headers + """ + data = values.of( + { + "AccountSid": account_sid, + "IsoCountry": iso_country, + "Status": status, + "FriendlyName": friendly_name, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ApplicationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ApplicationPage: + """ + Retrieve a specific page of ApplicationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ApplicationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ApplicationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ApplicationPage: + """ + Asynchronously retrieve a specific page of ApplicationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ApplicationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ApplicationPage(self._version, response) + + def get(self, sid: str) -> ApplicationContext: + """ + Constructs a ApplicationContext + + :param sid: The unique string that identifies the Short Code Application resource. + """ + return ApplicationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ApplicationContext: + """ + Constructs a ApplicationContext + + :param sid: The unique string that identifies the Short Code Application resource. + """ + return ApplicationContext(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/__init__.py b/twilio/rest/numbers/v2/authorization_document/__init__.py new file mode 100644 index 0000000000..8956774fa8 --- /dev/null +++ b/twilio/rest/numbers/v2/authorization_document/__init__.py @@ -0,0 +1,1074 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the AuthorizationDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthorizationDocumentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthorizationDocumentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthorizationDocumentInstance: + """ + Fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + payload, _, _ = self._fetch() + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthorizationDocumentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AuthorizationDocumentInstance: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + payload, _, _ = await self._fetch_async() + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + address_sid=address_sid, + email=email, + contact_phone_number=contact_phone_number, + hosted_number_order_sids=hosted_number_order_sids, + contact_title=contact_title, + cc_emails=cc_emails, + ) + return AuthorizationDocumentInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the AuthorizationDocumentInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + address_sid=address_sid, + email=email, + contact_phone_number=contact_phone_number, + hosted_number_order_sids=hosted_number_order_sids, + contact_title=contact_title, + cc_emails=cc_emails, + ) + instance = AuthorizationDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + address_sid=address_sid, + email=email, + contact_phone_number=contact_phone_number, + hosted_number_order_sids=hosted_number_order_sids, + contact_title=contact_title, + cc_emails=cc_emails, + ) + return AuthorizationDocumentInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the AuthorizationDocumentInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + address_sid=address_sid, + email=email, + contact_phone_number=contact_phone_number, + hosted_number_order_sids=hosted_number_order_sids, + contact_title=contact_title, + cc_emails=cc_emails, + ) + instance = AuthorizationDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AuthorizationDocumentInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + email=email, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AuthorizationDocumentInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + email=email, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AuthorizationDocumentInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AuthorizationDocumentInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with AuthorizationDocumentPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AuthorizationDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with AuthorizationDocumentPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AuthorizationDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..eed80d038f --- /dev/null +++ b/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py @@ -0,0 +1,711 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams DependentHostedNumberOrderInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams DependentHostedNumberOrderInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists DependentHostedNumberOrderInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists DependentHostedNumberOrderInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution + ) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with DependentHostedNumberOrderPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with DependentHostedNumberOrderPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..7ff4f50a40 --- /dev/null +++ b/twilio/rest/numbers/v2/bulk_hosted_number_order.py @@ -0,0 +1,435 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info( + self, order_status: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the BulkHostedNumberOrderInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + order_status=order_status, + ) + + async def fetch_with_http_info_async( + self, order_status: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BulkHostedNumberOrderInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "OrderStatus": order_status, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = self._fetch(order_status=order_status) + return BulkHostedNumberOrderInstance( + self._version, + payload, + bulk_hosting_sid=self._solution["bulk_hosting_sid"], + ) + + def fetch_with_http_info( + self, order_status: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the BulkHostedNumberOrderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(order_status=order_status) + instance = BulkHostedNumberOrderInstance( + self._version, + payload, + bulk_hosting_sid=self._solution["bulk_hosting_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, order_status: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "OrderStatus": order_status, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(order_status=order_status) + return BulkHostedNumberOrderInstance( + self._version, + payload, + bulk_hosting_sid=self._solution["bulk_hosting_sid"], + ) + + async def fetch_with_http_info_async( + self, order_status: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BulkHostedNumberOrderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + order_status=order_status + ) + instance = BulkHostedNumberOrderInstance( + self._version, + payload, + bulk_hosting_sid=self._solution["bulk_hosting_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, body: Union[object, object] = values.unset + ) -> BulkHostedNumberOrderInstance: + """ + Create the BulkHostedNumberOrderInstance + + :param body: + + :returns: The created BulkHostedNumberOrderInstance + """ + payload, _, _ = self._create(body=body) + return BulkHostedNumberOrderInstance(self._version, payload) + + def create_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the BulkHostedNumberOrderInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body) + instance = BulkHostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> BulkHostedNumberOrderInstance: + """ + Asynchronously create the BulkHostedNumberOrderInstance + + :param body: + + :returns: The created BulkHostedNumberOrderInstance + """ + payload, _, _ = await self._create_async(body=body) + return BulkHostedNumberOrderInstance(self._version, payload) + + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the BulkHostedNumberOrderInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(body=body) + instance = BulkHostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..7cee570fb3 --- /dev/null +++ b/twilio/rest/numbers/v2/bundle_clone.py @@ -0,0 +1,410 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.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 create_with_http_info( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the BundleCloneInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, + ) + + async def create_with_http_info_async( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the BundleCloneInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "TargetAccountSid": target_account_sid, + "MoveToDraft": serialize.boolean_to_string(move_to_draft), + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + target_account_sid=target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, + ) + return BundleCloneInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def create_with_http_info( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the BundleCloneInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + target_account_sid=target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, + ) + instance = BundleCloneInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "TargetAccountSid": target_account_sid, + "MoveToDraft": serialize.boolean_to_string(move_to_draft), + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + target_account_sid=target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, + ) + return BundleCloneInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_with_http_info_async( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the BundleCloneInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + target_account_sid=target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, + ) + instance = BundleCloneInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..dce5e77367 --- /dev/null +++ b/twilio/rest/numbers/v2/hosted_number_order.py @@ -0,0 +1,1616 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the HostedNumberOrderInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) + + async def update_with_http_info_async( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the HostedNumberOrderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> HostedNumberOrderInstance: + """ + Fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + payload, _, _ = self._fetch() + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the HostedNumberOrderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> HostedNumberOrderInstance: + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + payload, _, _ = await self._fetch_async() + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def update_with_http_info( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the HostedNumberOrderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) + instance = HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_async( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) + instance = HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + phone_number=phone_number, + contact_phone_number=contact_phone_number, + address_sid=address_sid, + email=email, + account_sid=account_sid, + friendly_name=friendly_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_capability=sms_capability, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + contact_title=contact_title, + ) + return HostedNumberOrderInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the HostedNumberOrderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + contact_phone_number=contact_phone_number, + address_sid=address_sid, + email=email, + account_sid=account_sid, + friendly_name=friendly_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_capability=sms_capability, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + contact_title=contact_title, + ) + instance = HostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + phone_number=phone_number, + contact_phone_number=contact_phone_number, + address_sid=address_sid, + email=email, + account_sid=account_sid, + friendly_name=friendly_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_capability=sms_capability, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + contact_title=contact_title, + ) + return HostedNumberOrderInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the HostedNumberOrderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + contact_phone_number=contact_phone_number, + address_sid=address_sid, + email=email, + account_sid=account_sid, + friendly_name=friendly_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_capability=sms_capability, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + contact_title=contact_title, + ) + instance = HostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams HostedNumberOrderInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams HostedNumberOrderInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists HostedNumberOrderInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists HostedNumberOrderInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with HostedNumberOrderPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = HostedNumberOrderPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with HostedNumberOrderPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = HostedNumberOrderPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 c53dcfcdd7..d917770b64 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py @@ -1,530 +1,1854 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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.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): + + class EndUserType(object): + INDIVIDUAL = "individual" + BUSINESS = "business" + + class SortBy(object): + VALID_UNTIL = "valid-until" + DATE_UPDATED = "date-updated" + + class SortDirection(object): + ASC = "ASC" + DESC = "DESC" + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + IN_REVIEW = "in-review" + TWILIO_REJECTED = "twilio-rejected" + TWILIO_APPROVED = "twilio-approved" + PROVISIONALLY_APPROVED = "provisionally-approved" + + """ + :ivar sid: The unique string that we created to identify the Bundle resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + :ivar regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar status: + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + :ivar email: The email address that will receive updates when the Bundle resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Bundle resource. + :ivar links: The URLs of the Assigned Items of the Bundle resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.regulation_sid: Optional[str] = payload.get("regulation_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["BundleInstance.Status"] = payload.get("status") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[BundleContext] = None - def __init__(self, version): + @property + def _proxy(self) -> "BundleContext": """ - Initialize the BundleList + 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: BundleContext for this BundleInstance + """ + if self._context is None: + self._context = BundleContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleList + def delete(self) -> bool: """ - super(BundleList, self).__init__(version) + Deletes the BundleInstance - # Path Solution - self._solution = {} - self._uri = '/RegulatoryCompliance/Bundles'.format(**self._solution) - 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): + :returns: True if delete succeeds, False otherwise """ - Create the BundleInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BundleInstance - :returns: The created BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Email': email, - 'StatusCallback': status_callback, - 'RegulationSid': regulation_sid, - 'IsoCountry': iso_country, - 'EndUserType': end_user_type, - 'NumberType': number_type, - }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BundleInstance with HTTP info - return BundleInstance(self._version, payload, ) - 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: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :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) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BundleInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - 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'], - ) + def fetch(self) -> "BundleInstance": + """ + Fetch the BundleInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - 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): + :returns: The fetched BundleInstance """ - Lists BundleInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return self._proxy.fetch() - :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) + async def fetch_async(self) -> "BundleInstance": + """ + Asynchronous coroutine to fetch the BundleInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance] + + :returns: The fetched BundleInstance """ - 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.fetch_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_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of BundleInstance records from the API. - Request is executed immediately + Fetch the BundleInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - 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_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BundleInstance with HTTP info - return BundlePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of BundleInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> "BundleInstance": + """ + Update the BundleInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundlePage + :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) + async def update_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> "BundleInstance": + """ + Asynchronous coroutine to update the BundleInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. - def get(self, sid): + :returns: The updated BundleInstance """ - Constructs a BundleContext + return await self._proxy.update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) - :param sid: The unique string that identifies the resource. + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the BundleInstance with HTTP info - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleContext - :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: ApiResponse with instance, status code, and headers """ - return BundleContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) - def __call__(self, sid): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Constructs a BundleContext + Asynchronous coroutine to update the BundleInstance with HTTP info - :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleContext + @property + def bundle_copies(self) -> BundleCopyList: + """ + Access the bundle_copies """ - return BundleContext(self._version, sid=sid, ) + return self._proxy.bundle_copies - def __repr__(self): + @property + def evaluations(self) -> EvaluationList: + """ + Access the evaluations + """ + return self._proxy.evaluations + + @property + def item_assignments(self) -> ItemAssignmentList: + """ + Access the item_assignments + """ + return self._proxy.item_assignments + + @property + def replace_items(self) -> ReplaceItemsList: + """ + Access the replace_items + """ + return self._proxy.replace_items + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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 + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{sid}".format(**self._solution) - def get_instance(self, payload): + self._bundle_copies: Optional[BundleCopyList] = None + self._evaluations: Optional[EvaluationList] = None + self._item_assignments: Optional[ItemAssignmentList] = None + self._replace_items: Optional[ReplaceItemsList] = None + + def _delete(self) -> tuple: """ - Build an instance of BundleInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :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): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the BundleInstance and return response metadata -class BundleContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the BundleContext - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource. + headers = values.of({}) - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(BundleContext, self).__init__(version) + Asynchronous coroutine that deletes the BundleInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RegulatoryCompliance/Bundles/{sid}'.format(**self._solution) - # Dependents - self._item_assignments = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BundleInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", 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, ) + payload, _, _ = self._fetch() + return BundleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BundleInstance and return response metadata - return BundleInstance(self._version, payload, sid=self._solution['sid'], ) - def update(self, status=values.unset, status_callback=values.unset, - friendly_name=values.unset, email=values.unset): + :returns: ApiResponse with instance, status code, and headers """ - Update the BundleInstance + payload, status_code, headers = self._fetch() + instance = BundleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :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 + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: The updated BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of({ - 'Status': status, - 'StatusCallback': status_callback, - 'FriendlyName': friendly_name, - 'Email': email, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers = values.of({}) - return BundleInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - @property - def item_assignments(self): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> BundleInstance: """ - Access the item_assignments + Asynchronous coroutine to fetch the BundleInstance + - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentList + :returns: The fetched BundleInstance """ - if self._item_assignments is None: - self._item_assignments = ItemAssignmentList(self._version, bundle_sid=self._solution['sid'], ) - return self._item_assignments + payload, _, _ = await self._fetch_async() + return BundleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the BundleInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BundleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Internal helper for update operation + Returns: + tuple: (payload, status_code, headers) + """ -class BundleInstance(InstanceResource): - """ """ + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + headers = values.of({}) - class Status(object): - DRAFT = "draft" - PENDING_REVIEW = "pending-review" - IN_REVIEW = "in-review" - TWILIO_REJECTED = "twilio-rejected" - TWILIO_APPROVED = "twilio-approved" + headers["Content-Type"] = "application/x-www-form-urlencoded" - class EndUserType(object): - INDIVIDUAL = "individual" - BUSINESS = "business" + headers["Accept"] = "application/json" - def __init__(self, version, payload, sid=None): + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - Initialize the BundleInstance + Update the BundleInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance + :returns: The updated BundleInstance """ - super(BundleInstance, self).__init__(version) + payload, _, _ = self._update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + return BundleInstance(self._version, payload, sid=self._solution["sid"]) - # 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'), - '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'), - } + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the BundleInstance and return response metadata - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + :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. - @property - def _proxy(self): + :returns: ApiResponse with instance, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, status_code, headers = self._update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + instance = BundleInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + headers = values.of({}) - :returns: BundleContext for this BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleContext + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - if self._context is None: - self._context = BundleContext(self._version, sid=self._solution['sid'], ) - return self._context + Asynchronous coroutine to update the BundleInstance - @property - def sid(self): + :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 + """ + payload, _, _ = await self._update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + return BundleInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: """ - :returns: The unique string that identifies the resource. - :rtype: unicode + Asynchronous coroutine to update the BundleInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['sid'] + payload, status_code, headers = await self._update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + instance = BundleInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def account_sid(self): + def bundle_copies(self) -> BundleCopyList: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Access the bundle_copies """ - return self._properties['account_sid'] + if self._bundle_copies is None: + self._bundle_copies = BundleCopyList( + self._version, + self._solution["sid"], + ) + return self._bundle_copies @property - def regulation_sid(self): + def evaluations(self) -> EvaluationList: """ - :returns: The unique string of a regulation. - :rtype: unicode + Access the evaluations """ - return self._properties['regulation_sid'] + if self._evaluations is None: + self._evaluations = EvaluationList( + self._version, + self._solution["sid"], + ) + return self._evaluations @property - def friendly_name(self): + def item_assignments(self) -> ItemAssignmentList: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Access the item_assignments """ - return self._properties['friendly_name'] + if self._item_assignments is None: + self._item_assignments = ItemAssignmentList( + self._version, + self._solution["sid"], + ) + return self._item_assignments @property - def status(self): + def replace_items(self) -> ReplaceItemsList: """ - :returns: The verification status of the Bundle resource - :rtype: BundleInstance.Status + Access the replace_items """ - return self._properties['status'] + if self._replace_items is None: + self._replace_items = ReplaceItemsList( + self._version, + self._solution["sid"], + ) + return self._replace_items - @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'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def status_callback(self): + +class BundlePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BundleInstance: """ - :returns: The URL we call to inform your application of status changes. - :rtype: unicode + Build an instance of BundleInstance + + :param payload: Payload response from the API """ - return self._properties['status_callback'] - @property - def date_created(self): + return BundleInstance(self._version, payload) + + def __repr__(self) -> str: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['date_created'] + return "" - @property - def date_updated(self): + +class BundleList(ListResource): + + def __init__(self, version: Version): """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Initialize the BundleList + + :param version: Version that contains the resource + """ - return self._properties['date_updated'] + super().__init__(version) - @property - def url(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, + ) -> tuple: """ - :returns: The absolute URL of the Bundle resource - :rtype: unicode + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['url'] - @property - def links(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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 URLs of the Assigned Items of the Bundle resource - :rtype: unicode + 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['links'] + payload, _, _ = self._create( + friendly_name=friendly_name, + email=email, + status_callback=status_callback, + regulation_sid=regulation_sid, + iso_country=iso_country, + end_user_type=end_user_type, + number_type=number_type, + is_test=is_test, + ) + return BundleInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the BundleInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + email=email, + status_callback=status_callback, + regulation_sid=regulation_sid, + iso_country=iso_country, + end_user_type=end_user_type, + number_type=number_type, + is_test=is_test, + ) + instance = BundleInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" - def fetch(self): + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - Fetch the BundleInstance + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + email=email, + status_callback=status_callback, + regulation_sid=regulation_sid, + iso_country=iso_country, + end_user_type=end_user_type, + number_type=number_type, + is_test=is_test, + ) + return BundleInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the BundleInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + email=email, + status_callback=status_callback, + regulation_sid=regulation_sid, + iso_country=iso_country, + end_user_type=end_user_type, + number_type=number_type, + is_test=is_test, + ) + instance = BundleInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, 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, + end_user_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BundleInstance]: + """ + Streams BundleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :returns: The fetched BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance + :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 bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :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 str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :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._proxy.fetch() + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + bundle_sids=bundle_sids, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + end_user_type=end_user_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, + bundle_sids: Union[str, 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, + end_user_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. - def update(self, status=values.unset, status_callback=values.unset, - friendly_name=values.unset, email=values.unset): + :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 bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :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 str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :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 """ - Update the BundleInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + bundle_sids=bundle_sids, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + end_user_type=end_user_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"], + ) - :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 + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, 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, + end_user_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, + ) -> tuple: + """ + Streams BundleInstance and returns headers from first page + + + :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 bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :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 str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + bundle_sids=bundle_sids, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + end_user_type=end_user_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"], + ) - :returns: The updated BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, 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, + end_user_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, + ) -> tuple: + """ + Asynchronously streams BundleInstance and returns headers from first page + + + :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 bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :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 str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._proxy.update( + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( status=status, - status_callback=status_callback, + bundle_sids=bundle_sids, friendly_name=friendly_name, - email=email, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + end_user_type=end_user_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 item_assignments(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, 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, + end_user_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]: """ - Access the item_assignments + 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 bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :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 str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :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, + bundle_sids=bundle_sids, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + end_user_type=end_user_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, + ) + ) - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentList + async def list_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, 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, + end_user_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 bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :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 str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :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, + bundle_sids=bundle_sids, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + end_user_type=end_user_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 list_with_http_info( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, 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, + end_user_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, + ) -> ApiResponse: + """ + Lists BundleInstance and returns headers from first page + + + :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 bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :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 str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + bundle_sids=bundle_sids, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + end_user_type=end_user_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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, 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, + end_user_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, + ) -> ApiResponse: + """ + Asynchronously lists BundleInstance and returns headers from first page + + + :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 bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :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 str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + bundle_sids=bundle_sids, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + end_user_type=end_user_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, 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, + end_user_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._proxy.item_assignments + 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 bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :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 end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :param has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BundleInstance + """ + data = values.of( + { + "Status": status, + "BundleSids": bundle_sids, + "FriendlyName": friendly_name, + "RegulationSid": regulation_sid, + "IsoCountry": iso_country, + "NumberType": number_type, + "EndUserType": end_user_type, + "HasValidUntilDate": serialize.boolean_to_string(has_valid_until_date), + "SortBy": sort_by, + "SortDirection": sort_direction, + "ValidUntilDate": serialize.iso8601_datetime(valid_until_date), + "ValidUntilDate<": serialize.iso8601_datetime(valid_until_date_before), + "ValidUntilDate>": serialize.iso8601_datetime(valid_until_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BundlePage(self._version, response) + + async def page_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, 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, + end_user_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 bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :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 end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :param has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BundleInstance + """ + data = values.of( + { + "Status": status, + "BundleSids": bundle_sids, + "FriendlyName": friendly_name, + "RegulationSid": regulation_sid, + "IsoCountry": iso_country, + "NumberType": number_type, + "EndUserType": end_user_type, + "HasValidUntilDate": serialize.boolean_to_string(has_valid_until_date), + "SortBy": sort_by, + "SortDirection": sort_direction, + "ValidUntilDate": serialize.iso8601_datetime(valid_until_date), + "ValidUntilDate<": serialize.iso8601_datetime(valid_until_date_before), + "ValidUntilDate>": serialize.iso8601_datetime(valid_until_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BundlePage(self._version, response) + + def page_with_http_info( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, 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, + end_user_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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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 bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :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 end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :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: ApiResponse with BundlePage, status code, and headers + """ + data = values.of( + { + "Status": status, + "BundleSids": bundle_sids, + "FriendlyName": friendly_name, + "RegulationSid": regulation_sid, + "IsoCountry": iso_country, + "NumberType": number_type, + "EndUserType": end_user_type, + "HasValidUntilDate": serialize.boolean_to_string(has_valid_until_date), + "SortBy": sort_by, + "SortDirection": sort_direction, + "ValidUntilDate": serialize.iso8601_datetime(valid_until_date), + "ValidUntilDate<": serialize.iso8601_datetime(valid_until_date_before), + "ValidUntilDate>": serialize.iso8601_datetime(valid_until_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BundlePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, 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, + end_user_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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 bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :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 end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :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: ApiResponse with BundlePage, status code, and headers + """ + data = values.of( + { + "Status": status, + "BundleSids": bundle_sids, + "FriendlyName": friendly_name, + "RegulationSid": regulation_sid, + "IsoCountry": iso_country, + "NumberType": number_type, + "EndUserType": end_user_type, + "HasValidUntilDate": serialize.boolean_to_string(has_valid_until_date), + "SortBy": sort_by, + "SortDirection": sort_direction, + "ValidUntilDate": serialize.iso8601_datetime(valid_until_date), + "ValidUntilDate<": serialize.iso8601_datetime(valid_until_date_before), + "ValidUntilDate>": serialize.iso8601_datetime(valid_until_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BundlePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> BundlePage: + """ + Retrieve a specific page of BundleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BundleInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BundlePage(self._version, response) + + async def get_page_async(self, target_url: str) -> BundlePage: + """ + Asynchronously retrieve a specific page of BundleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BundleInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BundlePage(self._version, response) + + def get(self, sid: str) -> BundleContext: + """ + Constructs a BundleContext + + :param sid: The unique string that we created to identify the Bundle resource. + """ + return BundleContext(self._version, sid=sid) + + def __call__(self, sid: str) -> BundleContext: + """ + Constructs a BundleContext + + :param sid: The unique string that we created to identify the Bundle resource. + """ + return BundleContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..d5f9d253c8 --- /dev/null +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py @@ -0,0 +1,608 @@ +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.api_response import ApiResponse + +from twilio.base.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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(friendly_name=friendly_name) + return BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def create_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the BundleCopyInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the copied bundle. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the BundleCopyInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the copied bundle. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BundleCopyInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BundleCopyInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BundleCopyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BundleCopyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BundleCopyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BundleCopyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BundleCopyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BundleCopyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py new file mode 100644 index 0000000000..34107f1ca8 --- /dev/null +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py @@ -0,0 +1,774 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EvaluationInstance(InstanceResource): + + class Status(object): + COMPLIANT = "compliant" + NONCOMPLIANT = "noncompliant" + + """ + :ivar sid: The unique string that identifies the Evaluation resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + :ivar regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :ivar bundle_sid: The unique string that we created to identify the Bundle resource. + :ivar status: + :ivar results: The results of the Evaluation which includes the valid and invalid attributes. + :ivar date_created: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + bundle_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.regulation_sid: Optional[str] = payload.get("regulation_sid") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.status: Optional["EvaluationInstance.Status"] = payload.get("status") + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "bundle_sid": bundle_sid, + "sid": sid or self.sid, + } + + self._context: Optional[EvaluationContext] = None + + @property + def _proxy(self) -> "EvaluationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EvaluationContext for this EvaluationInstance + """ + if self._context is None: + self._context = EvaluationContext( + self._version, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "EvaluationInstance": + """ + Fetch the EvaluationInstance + + + :returns: The fetched EvaluationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EvaluationInstance": + """ + Asynchronous coroutine to fetch the EvaluationInstance + + + :returns: The fetched EvaluationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EvaluationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EvaluationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EvaluationContext(InstanceContext): + + def __init__(self, version: Version, bundle_sid: str, sid: str): + """ + Initialize the EvaluationContext + + :param version: Version that contains the resource + :param bundle_sid: The unique string that we created to identify the Bundle resource. + :param sid: The unique string that identifies the Evaluation resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + "sid": sid, + } + self._uri = ( + "/RegulatoryCompliance/Bundles/{bundle_sid}/Evaluations/{sid}".format( + **self._solution + ) + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EvaluationInstance: + """ + Fetch the EvaluationInstance + + + :returns: The fetched EvaluationInstance + """ + payload, _, _ = self._fetch() + return EvaluationInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EvaluationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EvaluationInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> EvaluationInstance: + """ + Asynchronous coroutine to fetch the EvaluationInstance + + + :returns: The fetched EvaluationInstance + """ + payload, _, _ = await self._fetch_async() + return EvaluationInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EvaluationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EvaluationInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 EvaluationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EvaluationInstance: + """ + Build an instance of EvaluationInstance + + :param payload: Payload response from the API + """ + + return EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EvaluationList(ListResource): + + def __init__(self, version: Version, bundle_sid: str): + """ + Initialize the EvaluationList + + :param version: Version that contains the resource + :param bundle_sid: The unique string that identifies the Bundle resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{bundle_sid}/Evaluations".format( + **self._solution + ) + + def _create(self) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, headers=headers + ) + + def create(self) -> EvaluationInstance: + """ + Create the EvaluationInstance + + + :returns: The created EvaluationInstance + """ + payload, _, _ = self._create() + return EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the EvaluationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, headers=headers + ) + + async def create_async(self) -> EvaluationInstance: + """ + Asynchronously create the EvaluationInstance + + + :returns: The created EvaluationInstance + """ + payload, _, _ = await self._create_async() + return EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the EvaluationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EvaluationInstance]: + """ + Streams EvaluationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EvaluationInstance]: + """ + Asynchronously streams EvaluationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EvaluationInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EvaluationInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EvaluationInstance]: + """ + Lists EvaluationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EvaluationInstance]: + """ + Asynchronously lists EvaluationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EvaluationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EvaluationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EvaluationPage: + """ + Retrieve a single page of EvaluationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EvaluationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EvaluationPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EvaluationPage: + """ + Asynchronously retrieve a single page of EvaluationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EvaluationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EvaluationPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EvaluationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EvaluationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EvaluationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EvaluationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> EvaluationPage: + """ + Retrieve a specific page of EvaluationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EvaluationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EvaluationPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> EvaluationPage: + """ + Asynchronously retrieve a specific page of EvaluationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EvaluationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EvaluationPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> EvaluationContext: + """ + Constructs a EvaluationContext + + :param sid: The unique string that identifies the Evaluation resource. + """ + return EvaluationContext( + self._version, bundle_sid=self._solution["bundle_sid"], sid=sid + ) + + def __call__(self, sid: str) -> EvaluationContext: + """ + Constructs a EvaluationContext + + :param sid: The unique string that identifies the Evaluation resource. + """ + return EvaluationContext( + self._version, bundle_sid=self._solution["bundle_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py index a62ca306aa..336ee64979 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,887 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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") - def __init__(self, version, bundle_sid): + self._solution = { + "bundle_sid": bundle_sid, + "sid": sid or self.sid, + } + + self._context: Optional[ItemAssignmentContext] = None + + @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 + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: """ - Create the ItemAssignmentInstance + Asynchronous coroutine that deletes the ItemAssignmentInstance - :param unicode object_sid: The sid of an object bag - :returns: The created ItemAssignmentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'ObjectSid': object_sid, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ItemAssignmentInstance with HTTP info - return ItemAssignmentInstance(self._version, payload, bundle_sid=self._solution['bundle_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ItemAssignmentInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "ItemAssignmentInstance": + """ + Fetch the ItemAssignmentInstance - return self._version.stream(page, limits['limit'], limits['page_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. + 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) -> "ItemAssignmentInstance": + """ + Asynchronous coroutine to fetch the ItemAssignmentInstance - :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 """ - 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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of ItemAssignmentInstance records from the API. - Request is executed immediately + Fetch the ItemAssignmentInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ItemAssignmentInstance with HTTP info - return ItemAssignmentPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of ItemAssignmentInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of ItemAssignmentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentPage + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ItemAssignmentContext(InstanceContext): + + def __init__(self, version: Version, bundle_sid: str, sid: str): """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Initialize the ItemAssignmentContext + + :param version: Version that contains the resource + :param bundle_sid: The unique string that we created to identify the Bundle resource. + :param sid: The unique string that we created to identify the Identity resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + "sid": sid, + } + self._uri = ( + "/RegulatoryCompliance/Bundles/{bundle_sid}/ItemAssignments/{sid}".format( + **self._solution + ) ) - return ItemAssignmentPage(self._version, response, self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation - def get(self, sid): + Returns: + tuple: (success_boolean, status_code, headers) """ - Constructs a ItemAssignmentContext - :param sid: The unique string that identifies the resource + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ItemAssignmentInstance - :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, ) + success, _, _ = self._delete() + return success - def __call__(self, sid): + def delete_with_http_info(self) -> ApiResponse: """ - Constructs a ItemAssignmentContext + Deletes the ItemAssignmentInstance and return response metadata - :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: ApiResponse with success boolean, status code, and headers """ - return ItemAssignmentContext(self._version, bundle_sid=self._solution['bundle_sid'], sid=sid, ) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __repr__(self): + async def _delete_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for delete operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (success_boolean, status_code, headers) """ - return '' + headers = values.of({}) -class ItemAssignmentPage(Page): - """ """ + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the ItemAssignmentPage + Asynchronous coroutine that deletes the ItemAssignmentInstance - :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. - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentPage - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentPage + :returns: True if delete succeeds, False otherwise """ - super(ItemAssignmentPage, self).__init__(version, response) + success, _, _ = await self._delete_async() + return success - # Path Solution - self._solution = solution + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ItemAssignmentInstance and return response metadata - def get_instance(self, payload): + + :returns: ApiResponse with success boolean, status code, and headers """ - Build an instance of ItemAssignmentInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentInstance + Returns: + tuple: (payload, status_code, headers) """ - return ItemAssignmentInstance(self._version, payload, bundle_sid=self._solution['bundle_sid'], ) - def __repr__(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ItemAssignmentInstance: """ - Provide a friendly representation + Fetch the ItemAssignmentInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched ItemAssignmentInstance """ - return '' + payload, _, _ = self._fetch() + return ItemAssignmentInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ItemAssignmentInstance and return response metadata -class ItemAssignmentContext(InstanceContext): - """ """ - def __init__(self, version, bundle_sid, sid): + :returns: ApiResponse with instance, status code, and headers """ - Initialize the ItemAssignmentContext + payload, status_code, headers = self._fetch() + instance = ItemAssignmentInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :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 + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentContext + Returns: + tuple: (payload, status_code, headers) """ - super(ItemAssignmentContext, self).__init__(version) - # Path Solution - self._solution = {'bundle_sid': bundle_sid, 'sid': sid, } - self._uri = '/RegulatoryCompliance/Bundles/{bundle_sid}/ItemAssignments/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ItemAssignmentInstance: """ - Fetch the ItemAssignmentInstance + Asynchronous coroutine to fetch the ItemAssignmentInstance + :returns: The fetched ItemAssignmentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - + payload, _, _ = await self._fetch_async() return ItemAssignmentInstance( self._version, payload, - bundle_sid=self._solution['bundle_sid'], - sid=self._solution['sid'], + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the ItemAssignmentInstance + Asynchronous coroutine to fetch the ItemAssignmentInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = ItemAssignmentInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 ItemAssignmentInstance(InstanceResource): - """ """ +class ItemAssignmentPage(Page): - def __init__(self, version, payload, bundle_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> ItemAssignmentInstance: """ - Initialize the ItemAssignmentInstance + Build an instance of ItemAssignmentInstance + + :param payload: Payload response from the API + """ + + 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 __repr__(self) -> str: """ - super(ItemAssignmentInstance, self).__init__(version) + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + - # 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'), +class ItemAssignmentList(ListResource): + + def __init__(self, version: Version, bundle_sid: str): + """ + Initialize the ItemAssignmentList + + :param version: Version that contains the resource + :param bundle_sid: The unique string that we created to identify the Bundle resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, } + self._uri = "/RegulatoryCompliance/Bundles/{bundle_sid}/ItemAssignments".format( + **self._solution + ) - # Context - self._context = None - self._solution = {'bundle_sid': bundle_sid, 'sid': sid or self._properties['sid'], } + def _create(self, object_sid: str) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: ItemAssignmentContext for this ItemAssignmentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, object_sid: str) -> ItemAssignmentInstance: """ - if self._context is None: - self._context = ItemAssignmentContext( - self._version, - bundle_sid=self._solution['bundle_sid'], - sid=self._solution['sid'], + Create the ItemAssignmentInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created ItemAssignmentInstance + """ + payload, _, _ = self._create(object_sid=object_sid) + return ItemAssignmentInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def create_with_http_info(self, object_sid: str) -> ApiResponse: + """ + Create the ItemAssignmentInstance and return response metadata + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(object_sid=object_sid) + instance = ItemAssignmentInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, object_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, object_sid: str) -> ItemAssignmentInstance: + """ + Asynchronously create the ItemAssignmentInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created ItemAssignmentInstance + """ + payload, _, _ = await self._create_async(object_sid=object_sid) + return ItemAssignmentInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_with_http_info_async(self, object_sid: str) -> ApiResponse: + """ + Asynchronously create the ItemAssignmentInstance and return response metadata + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(object_sid=object_sid) + instance = ItemAssignmentInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ItemAssignmentInstance]: + """ + Streams ItemAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ItemAssignmentInstance]: + """ + Asynchronously streams ItemAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ItemAssignmentInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ItemAssignmentInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ItemAssignmentInstance]: + """ + Lists ItemAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def 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 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['sid'] - @property - def bundle_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The unique string that identifies the Bundle resource. - :rtype: unicode + Lists ItemAssignmentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['bundle_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def account_sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Asynchronously lists ItemAssignmentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['account_sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def object_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 an object bag - :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['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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ItemAssignmentPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ItemAssignmentPage: + """ + Asynchronously retrieve a single page of ItemAssignmentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ItemAssignmentInstance """ - :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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ItemAssignmentPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_created'] + Retrieve a single page with response metadata - @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: ApiResponse with ItemAssignmentPage, status code, and headers """ - :returns: The absolute URL of the Identity 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ItemAssignmentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['url'] + Asynchronously retrieve a single page with response metadata - 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: ApiResponse with ItemAssignmentPage, status code, and headers """ - Fetch the ItemAssignmentInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: The fetched ItemAssignmentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentInstance + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ItemAssignmentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ItemAssignmentPage: """ - return self._proxy.fetch() + Retrieve a specific page of ItemAssignmentInstance 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 ItemAssignmentInstance """ - Deletes the ItemAssignmentInstance + response = self._version.domain.twilio.request("GET", target_url) + return ItemAssignmentPage(self._version, response, solution=self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def get_page_async(self, target_url: str) -> ItemAssignmentPage: """ - return self._proxy.delete() + Asynchronously retrieve a specific page of ItemAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ItemAssignmentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ItemAssignmentPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> ItemAssignmentContext: + """ + Constructs a ItemAssignmentContext + + :param sid: The unique string that we created to identify the Identity resource. + """ + return ItemAssignmentContext( + self._version, bundle_sid=self._solution["bundle_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ItemAssignmentContext: + """ + Constructs a ItemAssignmentContext + + :param sid: The unique string that we created to identify the Identity resource. + """ + return ItemAssignmentContext( + self._version, bundle_sid=self._solution["bundle_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..cb9c9a46dd --- /dev/null +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py @@ -0,0 +1,210 @@ +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.api_response import ApiResponse + +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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(from_bundle_sid=from_bundle_sid) + return ReplaceItemsInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def create_with_http_info(self, from_bundle_sid: str) -> ApiResponse: + """ + Create the ReplaceItemsInstance and return response metadata + + :param from_bundle_sid: The source bundle sid to copy the item assignments from. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(from_bundle_sid=from_bundle_sid) + instance = ReplaceItemsInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, from_bundle_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(from_bundle_sid=from_bundle_sid) + return ReplaceItemsInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_with_http_info_async(self, from_bundle_sid: str) -> ApiResponse: + """ + Asynchronously create the ReplaceItemsInstance and return response metadata + + :param from_bundle_sid: The source bundle sid to copy the item assignments from. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + from_bundle_sid=from_bundle_sid + ) + instance = ReplaceItemsInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 3448304890..eaf2f958f2 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/end_user.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/end_user.py @@ -1,400 +1,1111 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + + class Type(object): + INDIVIDUAL = "individual" + BUSINESS = "business" + + """ + :ivar sid: The unique string created by Twilio to identify the End User resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the End User resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar attributes: The set of parameters that are the attributes of the End Users resource which are listed in the End User Types. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the End User resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["EndUserInstance.Type"] = payload.get("type") + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") - def __init__(self, version): + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[EndUserContext] = None + + @property + def _proxy(self) -> "EndUserContext": """ - Initialize the EndUserList + 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: EndUserContext for this EndUserInstance + """ + if self._context is None: + self._context = EndUserContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserList + def delete(self) -> bool: """ - super(EndUserList, self).__init__(version) + Deletes the EndUserInstance - # Path Solution - self._solution = {} - self._uri = '/RegulatoryCompliance/EndUsers'.format(**self._solution) - def create(self, friendly_name, type, attributes=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the EndUserInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EndUserInstance - :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 await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EndUserInstance with HTTP info - return EndUserInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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 self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EndUserInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "EndUserInstance": + """ + Fetch the EndUserInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "EndUserInstance": + """ + Asynchronous coroutine to fetch the EndUserInstance - :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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of EndUserInstance records from the API. - Request is executed immediately + Fetch the EndUserInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserPage + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserInstance with HTTP info - return EndUserPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of EndUserInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "EndUserInstance": + """ + Update the EndUserInstance - :returns: Page of EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserPage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + friendly_name=friendly_name, + attributes=attributes, ) - return EndUserPage(self._version, response, self._solution) + 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. - def get(self, sid): + :returns: The updated EndUserInstance """ - Constructs a EndUserContext + return await self._proxy.update_async( + friendly_name=friendly_name, + attributes=attributes, + ) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the EndUserInstance with HTTP info - :param sid: The unique string that identifies the 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: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext + :returns: ApiResponse with instance, status code, and headers """ - return EndUserContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + attributes=attributes, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: """ - Constructs a EndUserContext + Asynchronous coroutine to update the EndUserInstance with HTTP info - :param sid: The unique string that identifies the 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: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext + :returns: ApiResponse with instance, status code, and headers """ - return EndUserContext(self._version, sid=sid, ) + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + attributes=attributes, + ) - 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 EndUserPage(Page): - """ """ +class EndUserContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the EndUserPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the EndUserContext - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserPage - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserPage + :param version: Version that contains the resource + :param sid: The unique string created by Twilio to identify the End User resource. """ - super(EndUserPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/EndUsers/{sid}".format(**self._solution) - def get_instance(self, payload): + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of EndUserInstance - :param dict payload: Payload response from the API + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance + def delete(self) -> bool: """ - return EndUserInstance(self._version, payload, ) + Deletes the EndUserInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the EndUserInstance and return response metadata -class EndUserContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: """ - Initialize the EndUserContext + Internal async helper for delete operation - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(EndUserContext, self).__init__(version) + Asynchronous coroutine that deletes the EndUserInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RegulatoryCompliance/EndUsers/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EndUserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EndUserInstance: """ Fetch the EndUserInstance + + :returns: The fetched EndUserInstance + """ + payload, _, _ = self._fetch() + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> EndUserInstance: + """ + Asynchronous coroutine to fetch the EndUserInstance + + :returns: The fetched EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = await self._fetch_async() + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - return EndUserInstance(self._version, payload, sid=self._solution['sid'], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserInstance and return response metadata - def update(self, friendly_name=values.unset, attributes=values.unset): + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: """ 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._update(friendly_name=friendly_name, attributes=attributes) + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the EndUserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, attributes=attributes + ) + instance = EndUserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + Returns: + tuple: (payload, status_code, headers) + """ - return EndUserInstance(self._version, payload, sid=self._solution['sid'], ) + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) - def __repr__(self): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the EndUserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) + instance = EndUserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide 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 - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance + return EndUserInstance(self._version, payload) + + 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, + ) -> tuple: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + 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 + 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 + """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return EndUserInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['account_sid'] + Create the EndUserInstance and return response metadata - @property - def friendly_name(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = EndUserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> tuple: """ - return self._properties['friendly_name'] + Internal async helper for create operation - @property - def type(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The type of end user of the Bundle resource - :rtype: EndUserInstance.Type + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: """ - return self._properties['type'] + Asynchronously create the EndUserInstance - @property - def attributes(self): + :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 """ - :returns: The set of parameters that compose the End Users resource - :rtype: dict + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return EndUserInstance(self._version, payload) + + async def create_with_http_info_async( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['attributes'] + Asynchronously create the EndUserInstance and return response metadata - @property - def date_created(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = EndUserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EndUserInstance]: """ - return self._properties['date_created'] + 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. - @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[EndUserInstance]: """ - return self._properties['date_updated'] + 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. - @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 End User 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['url'] + Streams EndUserInstance and returns headers from first page + - 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: tuple of (generator, status_code, headers) where generator yields instances """ - Fetch the EndUserInstance + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: The fetched EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._proxy.fetch() + Asynchronously streams EndUserInstance and returns headers from first page - def update(self, friendly_name=values.unset, attributes=values.unset): + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Update the EndUserInstance + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :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 + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: The updated EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EndUserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EndUserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EndUserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EndUserPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EndUserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EndUserPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 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 6fd9f437a6..cf6534bbed 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,649 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 + 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: EndUserTypeContext for this EndUserTypeInstance + """ + if self._context is None: + self._context = EndUserTypeContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeList + def fetch(self) -> "EndUserTypeInstance": """ - super(EndUserTypeList, self).__init__(version) + Fetch the EndUserTypeInstance - # Path Solution - self._solution = {} - self._uri = '/RegulatoryCompliance/EndUserTypes'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "EndUserTypeInstance": + """ + Asynchronous coroutine to fetch the EndUserTypeInstance - :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 await self._proxy.fetch_async() - page = self.page(page_size=limits['page_size'], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserTypeInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with instance, status code, and headers """ - Lists EndUserTypeInstance 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_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeInstance] + + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_with_http_info_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 EndUserTypeInstance 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 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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - Retrieve a specific page of EndUserTypeInstance records from the API. - Request is executed immediately - :param str target_url: API-generated URL for the requested results page + headers = values.of({}) - :returns: Page of EndUserTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypePage + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EndUserTypeInstance: + """ + Fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + payload, _, _ = self._fetch() + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return EndUserTypePage(self._version, response, self._solution) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserTypeInstance and return response metadata + - def get(self, sid): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a EndUserTypeContext + payload, status_code, headers = self._fetch() + instance = EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :param sid: The unique string that identifies the End-User Type resource + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeContext + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> EndUserTypeInstance: """ - return EndUserTypeContext(self._version, sid=sid, ) + Asynchronous coroutine to fetch the EndUserTypeInstance + - def __call__(self, sid): + :returns: The fetched EndUserTypeInstance """ - Constructs a EndUserTypeContext + payload, _, _ = await self._fetch_async() + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return EndUserTypeContext(self._version, sid=sid, ) + payload, status_code, headers = await self._fetch_async() + instance = EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 EndUserTypePage(Page): - """ """ - def __init__(self, version, response, solution): + def get_instance(self, payload: Dict[str, Any]) -> EndUserTypeInstance: """ - Initialize the EndUserTypePage + Build an instance of EndUserTypeInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API + :param payload: Payload response from the API + """ + + return EndUserTypeInstance(self._version, payload) - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypePage - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypePage + def __repr__(self) -> str: """ - super(EndUserTypePage, self).__init__(version, response) + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" - # Path Solution - self._solution = solution - def get_instance(self, payload): +class EndUserTypeList(ListResource): + + def __init__(self, version: Version): """ - Build an instance of EndUserTypeInstance + Initialize the EndUserTypeList - :param dict payload: Payload response from the API + :param version: Version that contains the resource - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeInstance """ - return EndUserTypeInstance(self._version, payload, ) + super().__init__(version) + + self._uri = "/RegulatoryCompliance/EndUserTypes" - def __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EndUserTypeInstance]: """ - Provide a friendly representation + 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 """ - return '' + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + return self._version.stream(page, limits["limit"]) -class EndUserTypeContext(InstanceContext): - """ """ + 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) - def __init__(self, version, sid): + :returns: Generator that will yield up to limit results """ - Initialize the EndUserTypeContext + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the End-User Type resource + return self._version.stream_async(page, limits["limit"]) - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeContext + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(EndUserTypeContext, self).__init__(version) + Streams EndUserTypeInstance and returns headers from first page - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RegulatoryCompliance/EndUserTypes/{sid}'.format(**self._solution) - 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: tuple of (generator, status_code, headers) where generator yields instances """ - Fetch the EndUserTypeInstance + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: The fetched EndUserTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeInstance + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronously streams EndUserTypeInstance and returns headers from first page + - return EndUserTypeInstance(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) - def __repr__(self): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Provide a friendly representation + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :returns: Machine friendly representation - :rtype: str + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserTypeInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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) -class EndUserTypeInstance(InstanceResource): - """ """ + :returns: list that will contain up to limit results + """ + + return 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. - 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 EndUserTypeInstance - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeInstance + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - super(EndUserTypeInstance, self).__init__(version) + Lists EndUserTypeInstance and returns headers from first page - # 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'), - } - # Context - self._context = None - self._solution = {'sid': sid or 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 _proxy(self): + :returns: ApiResponse with list of instances, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: EndUserTypeContext for this EndUserTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeContext + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - if self._context is None: - self._context = EndUserTypeContext(self._version, sid=self._solution['sid'], ) - return self._context + Asynchronously lists EndUserTypeInstance and returns headers from first page - @property - def 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: ApiResponse with list of instances, status code, and headers """ - :returns: The unique string that identifies the End-User Type resource - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['sid'] + Retrieve a single page of EndUserTypeInstance records from the API. + Request is executed immediately - @property - def friendly_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 EndUserTypeInstance """ - :returns: A human-readable description of the End-User Type 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 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: """ - return self._properties['friendly_name'] + Asynchronously retrieve a single page of EndUserTypeInstance records from the API. + Request is executed immediately - @property - def machine_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 EndUserTypeInstance """ - :returns: A machine-readable description of the End-User Type 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 EndUserTypePage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['machine_name'] + Retrieve a single page with response metadata - @property - def fields(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: ApiResponse with EndUserTypePage, status code, and headers """ - :returns: The required information for creating an End-User. - :rtype: dict + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EndUserTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['fields'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with EndUserTypePage, status code, and headers """ - :returns: The absolute URL of the End-User Type 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EndUserTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> EndUserTypePage: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of EndUserTypeInstance """ - Fetch the EndUserTypeInstance + response = self._version.domain.twilio.request("GET", target_url) + return EndUserTypePage(self._version, response) - :returns: The fetched EndUserTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeInstance + async def get_page_async(self, target_url: str) -> EndUserTypePage: """ - return self._proxy.fetch() + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 1be37685c3..88a84f8518 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/regulation.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/regulation.py @@ -1,370 +1,860 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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" - :param Version version: Version that contains the resource + """ + :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") - :returns: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationList - """ - super(RegulationList, self).__init__(version) + self._solution = { + "sid": sid or self.sid, + } - # Path Solution - self._solution = {} - self._uri = '/RegulatoryCompliance/Regulations'.format(**self._solution) + self._context: Optional[RegulationContext] = None - def stream(self, end_user_type=values.unset, iso_country=values.unset, - number_type=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "RegulationContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :returns: RegulationContext for this RegulationInstance + """ + if self._context is None: + self._context = RegulationContext( + 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.regulation.RegulationInstance] + def fetch( + self, include_constraints: Union[bool, object] = values.unset + ) -> "RegulationInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the RegulationInstance - page = self.page( - end_user_type=end_user_type, - iso_country=iso_country, - number_type=number_type, - page_size=limits['page_size'], - ) + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched RegulationInstance + """ + return self._proxy.fetch( + include_constraints=include_constraints, + ) - 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 fetch_with_http_info( + self, include_constraints: Union[bool, object] = values.unset + ) -> ApiResponse: """ - Retrieve a single page of RegulationInstance records from the API. - Request is executed immediately + Fetch the RegulationInstance with HTTP info - :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 + :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: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'EndUserType': end_user_type, - 'IsoCountry': iso_country, - 'NumberType': number_type, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return RegulationPage(self._version, response, self._solution) + return self._proxy.fetch_with_http_info( + include_constraints=include_constraints, + ) - def get_page(self, target_url): + async def fetch_with_http_info_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> ApiResponse: """ - Retrieve a specific page of RegulationInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the RegulationInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.fetch_with_http_info_async( + include_constraints=include_constraints, ) - return RegulationPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a RegulationContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The unique string that identifies the Regulation resource - :returns: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationContext +class RegulationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - return RegulationContext(self._version, sid=sid, ) + Initialize the RegulationContext - def __call__(self, sid): + :param version: Version that contains the resource + :param sid: The unique string that identifies the Regulation resource. """ - Constructs a RegulationContext + super().__init__(version) - :param sid: The unique string that identifies the Regulation resource + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/Regulations/{sid}".format(**self._solution) - :returns: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationContext + def _fetch(self, include_constraints: Union[bool, object] = values.unset) -> tuple: """ - return RegulationContext(self._version, sid=sid, ) + Internal helper for fetch operation - def __repr__(self): + Returns: + tuple: (payload, status_code, headers) """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - return '' + params = values.of( + { + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + } + ) + headers = values.of({}) -class RegulationPage(Page): - """ """ + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) - def __init__(self, version, response, solution): + def fetch( + self, include_constraints: Union[bool, object] = values.unset + ) -> RegulationInstance: """ - Initialize the RegulationPage + Fetch the RegulationInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API + :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.RegulationPage - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationPage + :returns: The fetched RegulationInstance """ - super(RegulationPage, self).__init__(version, response) + payload, _, _ = self._fetch(include_constraints=include_constraints) + return RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - # Path Solution - self._solution = solution + def fetch_with_http_info( + self, include_constraints: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the RegulationInstance and return response metadata - def get_instance(self, payload): + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of RegulationInstance + payload, status_code, headers = self._fetch( + include_constraints=include_constraints + ) + instance = RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + async def _fetch_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation - :returns: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationInstance + Returns: + tuple: (payload, status_code, headers) """ - return RegulationInstance(self._version, payload, ) - def __repr__(self): + params = values.of( + { + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + async def fetch_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> RegulationInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the RegulationInstance - :returns: Machine friendly representation - :rtype: str + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: The fetched RegulationInstance """ - return '' + payload, _, _ = await self._fetch_async(include_constraints=include_constraints) + return RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + async def fetch_with_http_info_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RegulationInstance and return response metadata -class RegulationContext(InstanceContext): - """ """ + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields - def __init__(self, version, sid): + :returns: ApiResponse with instance, status code, and headers """ - Initialize the RegulationContext + payload, status_code, headers = await self._fetch_async( + include_constraints=include_constraints + ) + instance = RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the Regulation resource + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationContext + :returns: Machine friendly representation """ - super(RegulationContext, self).__init__(version) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RegulatoryCompliance/Regulations/{sid}'.format(**self._solution) - def fetch(self): +class RegulationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RegulationInstance: """ - Fetch the RegulationInstance + Build an instance of RegulationInstance - :returns: The fetched RegulationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationInstance + :param payload: Payload response from the API """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return RegulationInstance(self._version, payload, sid=self._solution['sid'], ) + return RegulationInstance(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 RegulationInstance(InstanceResource): - """ """ +class RegulationList(ListResource): - class EndUserType(object): - INDIVIDUAL = "individual" - BUSINESS = "business" + def __init__(self, version: Version): + """ + Initialize the RegulationList + + :param version: Version that contains the resource - def __init__(self, version, payload, sid=None): """ - Initialize the RegulationInstance + super().__init__(version) - :returns: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationInstance + self._uri = "/RegulatoryCompliance/Regulations" + + def stream( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RegulationInstance]: """ - super(RegulationInstance, self).__init__(version) + 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. - # 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'), - } + :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) - # Context - self._context = None - self._solution = {'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( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + page_size=limits["page_size"], + ) - @property - def _proxy(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RegulationInstance]: """ - 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 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: RegulationContext for this RegulationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationContext + :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 """ - if self._context is None: - self._context = RegulationContext(self._version, sid=self._solution['sid'], ) - return self._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"], + ) - @property - def sid(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: """ - :returns: The unique string that identifies the Regulation resource - :rtype: unicode + Streams RegulationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + page_size=limits["page_size"], + ) - @property - def friendly_name(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - :returns: A human-readable description of the Regulation resource - :rtype: unicode + Asynchronously streams RegulationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + page_size=limits["page_size"], + ) - @property - def iso_country(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - :returns: The ISO country code of the phone number's country - :rtype: unicode + Lists RegulationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RegulationInstance]: + """ + Asynchronously lists RegulationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists RegulationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists RegulationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['iso_country'] + Retrieve a single page of RegulationInstance records from the API. + Request is executed immediately - @property - def number_type(self): + :param end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param iso_country: The ISO country code of the phone number's country. + :param number_type: The type of phone number that the regulatory requiremnt is restricting. + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RegulationInstance """ - :returns: The type of phone number restricted by the regulatory requirement - :rtype: unicode + data = values.of( + { + "EndUserType": end_user_type, + "IsoCountry": iso_country, + "NumberType": number_type, + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RegulationPage(self._version, response) + + async def page_async( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RegulationPage: + """ + Asynchronously retrieve a single page of RegulationInstance records from the API. + Request is executed immediately + + :param end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param iso_country: The ISO country code of the phone number's country. + :param number_type: The type of phone number that the regulatory requiremnt is restricting. + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RegulationInstance """ - return self._properties['number_type'] + 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 end_user_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 RegulationPage(self._version, response) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with RegulationPage, status code, and headers + """ + data = values.of( + { + "EndUserType": end_user_type, + "IsoCountry": iso_country, + "NumberType": number_type, + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RegulationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with RegulationPage, status code, and headers + """ + data = values.of( + { + "EndUserType": end_user_type, + "IsoCountry": iso_country, + "NumberType": number_type, + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RegulationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 ca0ee1dc7c..abbddb13c1 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py @@ -1,421 +1,1135 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + REJECTED = "rejected" + APPROVED = "approved" + EXPIRED = "expired" + PROVISIONALLY_APPROVED = "provisionally-approved" + + """ + :ivar sid: The unique string created by Twilio to identify the Supporting Document resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Document resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar mime_type: The image type uploaded in the Supporting Document container. + :ivar status: + :ivar failure_reason: The failure reason of the Supporting Document Resource. + :ivar errors: A list of errors that occurred during the registering RC Bundle + :ivar type: The type of the Supporting Document. + :ivar attributes: The set of parameters that are the attributes of the Supporting Documents resource which are listed in the Supporting Document Types. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Supporting Document resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.mime_type: Optional[str] = payload.get("mime_type") + self.status: Optional["SupportingDocumentInstance.Status"] = payload.get( + "status" + ) + self.failure_reason: Optional[str] = payload.get("failure_reason") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + self.type: Optional[str] = payload.get("type") + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[SupportingDocumentContext] = None + + @property + def _proxy(self) -> "SupportingDocumentContext": """ - Initialize the SupportingDocumentList + 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: SupportingDocumentContext for this SupportingDocumentInstance + """ + if self._context is None: + self._context = SupportingDocumentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentList + def delete(self) -> bool: """ - super(SupportingDocumentList, self).__init__(version) + Deletes the SupportingDocumentInstance - # Path Solution - self._solution = {} - self._uri = '/RegulatoryCompliance/SupportingDocuments'.format(**self._solution) - def create(self, friendly_name, type, attributes=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the SupportingDocumentInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance - :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 await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SupportingDocumentInstance with HTTP info - return SupportingDocumentInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "SupportingDocumentInstance": + """ + Fetch the SupportingDocumentInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "SupportingDocumentInstance": + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance - :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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of SupportingDocumentInstance records from the API. - Request is executed immediately + Fetch the SupportingDocumentInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentPage + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance with HTTP info - return SupportingDocumentPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of SupportingDocumentInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "SupportingDocumentInstance": + """ + Update the SupportingDocumentInstance - :returns: Page of SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentPage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + friendly_name=friendly_name, + attributes=attributes, ) - return SupportingDocumentPage(self._version, response, self._solution) + 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. - def get(self, sid): + :returns: The updated SupportingDocumentInstance """ - Constructs a SupportingDocumentContext + return await self._proxy.update_async( + friendly_name=friendly_name, + attributes=attributes, + ) - :param sid: The unique string that identifies the resource + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the SupportingDocumentInstance with HTTP info - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentContext + :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: ApiResponse with instance, status code, and headers """ - return SupportingDocumentContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + attributes=attributes, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: """ - Constructs a SupportingDocumentContext + Asynchronous coroutine to update the SupportingDocumentInstance with HTTP info - :param sid: The unique string that identifies the 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: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentContext + :returns: ApiResponse with instance, status code, and headers """ - return SupportingDocumentContext(self._version, sid=sid, ) + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + attributes=attributes, + ) - 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 SupportingDocumentPage(Page): - """ """ +class SupportingDocumentContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the SupportingDocumentPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the SupportingDocumentContext - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentPage - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentPage + :param version: Version that contains the resource + :param sid: The unique string created by Twilio to identify the Supporting Document resource. """ - super(SupportingDocumentPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/SupportingDocuments/{sid}".format( + **self._solution + ) - def get_instance(self, payload): + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of SupportingDocumentInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return SupportingDocumentInstance(self._version, payload, ) + Deletes the SupportingDocumentInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the SupportingDocumentInstance and return response metadata -class SupportingDocumentContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: """ - Initialize the SupportingDocumentContext + Internal async helper for delete operation - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentContext + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(SupportingDocumentContext, self).__init__(version) + Asynchronous coroutine that deletes the SupportingDocumentInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RegulatoryCompliance/SupportingDocuments/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SupportingDocumentInstance: """ Fetch the SupportingDocumentInstance + :returns: The fetched SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentInstance and return response metadata - return SupportingDocumentInstance(self._version, payload, sid=self._solution['sid'], ) - def update(self, friendly_name=values.unset, attributes=values.unset): + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SupportingDocumentInstance: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + payload, _, _ = await self._fetch_async() + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: """ 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 + """ + payload, _, _ = self._update(friendly_name=friendly_name, attributes=attributes) + return SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the SupportingDocumentInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, attributes=attributes + ) + instance = SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance """ - data = values.of({'FriendlyName': friendly_name, 'Attributes': serialize.object(attributes), }) + payload, _, _ = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) + return SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SupportingDocumentInstance and return response metadata - return SupportingDocumentInstance(self._version, payload, sid=self._solution['sid'], ) + :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. - def __repr__(self): + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) + instance = SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide 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" + 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 - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance + return SupportingDocumentInstance(self._version, payload) + + 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): +class SupportingDocumentList(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 SupportingDocumentList + + :param version: Version that contains the resource - :returns: SupportingDocumentContext for this SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentContext """ - if self._context is None: - self._context = SupportingDocumentContext(self._version, sid=self._solution['sid'], ) - return self._context + super().__init__(version) - @property - def sid(self): + self._uri = "/RegulatoryCompliance/SupportingDocuments" + + def _create( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> tuple: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - :returns: The SID of the Account that created the resource - :rtype: unicode + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return SupportingDocumentInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['account_sid'] + Create the SupportingDocumentInstance and return response metadata - @property - def friendly_name(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = SupportingDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> tuple: """ - return self._properties['friendly_name'] + Internal async helper for create operation - @property - def mime_type(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The image type of the file - :rtype: unicode + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: """ - return self._properties['mime_type'] + Asynchronously create the SupportingDocumentInstance - @property - def status(self): + :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 """ - :returns: The verification status of the Supporting Document resource - :rtype: SupportingDocumentInstance.Status + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return SupportingDocumentInstance(self._version, payload) + + async def create_with_http_info_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['status'] + Asynchronously create the SupportingDocumentInstance and return response metadata - @property - def type(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The type of the Supporting Document - :rtype: unicode + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = SupportingDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SupportingDocumentInstance]: """ - return self._properties['type'] + 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. - @property - def attributes(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 set of parameters that compose the Supporting Documents resource - :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[SupportingDocumentInstance]: """ - return self._properties['attributes'] + 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. - @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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_created'] + Streams SupportingDocumentInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :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_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_updated'] + Asynchronously streams SupportingDocumentInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The absolute URL of the Supporting Document resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentInstance]: """ - return self._properties['url'] + Lists SupportingDocumentInstance 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 SupportingDocumentInstance - :returns: The fetched SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance + return 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]: """ - return self._proxy.fetch() + 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) - def update(self, friendly_name=values.unset, attributes=values.unset): + :returns: list that will contain up to limit results """ - 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 + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SupportingDocumentInstance and returns headers from first page - :returns: The updated SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SupportingDocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SupportingDocumentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SupportingDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SupportingDocumentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SupportingDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 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 2893b05afc..d2de945f94 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,651 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 + 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: SupportingDocumentTypeContext for this SupportingDocumentTypeInstance + """ + if self._context is None: + self._context = SupportingDocumentTypeContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeList + def fetch(self) -> "SupportingDocumentTypeInstance": """ - super(SupportingDocumentTypeList, self).__init__(version) + Fetch the SupportingDocumentTypeInstance - # Path Solution - self._solution = {} - self._uri = '/RegulatoryCompliance/SupportingDocumentTypes'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "SupportingDocumentTypeInstance": + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance - :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 await self._proxy.fetch_async() - page = self.page(page_size=limits['page_size'], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentTypeInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with instance, status code, and headers """ - Lists SupportingDocumentTypeInstance 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_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeInstance] + + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_with_http_info_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 SupportingDocumentTypeInstance 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 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) -> tuple: """ - Retrieve a specific page of SupportingDocumentTypeInstance records from the API. - Request is executed immediately + Internal helper for fetch operation - :param str target_url: API-generated URL for the requested results page + Returns: + tuple: (payload, status_code, headers) + """ - :returns: Page of SupportingDocumentTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypePage + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SupportingDocumentTypeInstance: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + payload, _, _ = self._fetch() + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SupportingDocumentTypePage(self._version, response, self._solution) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentTypeInstance and return response metadata + - def get(self, sid): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a SupportingDocumentTypeContext + payload, status_code, headers = self._fetch() + instance = SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) - :param sid: The unique string that identifies the Supporting Document Type resource + headers["Accept"] = "application/json" - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeContext + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SupportingDocumentTypeInstance: """ - return SupportingDocumentTypeContext(self._version, sid=sid, ) + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance + - def __call__(self, sid): + :returns: The fetched SupportingDocumentTypeInstance """ - Constructs a SupportingDocumentTypeContext + payload, _, _ = await self._fetch_async() + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return SupportingDocumentTypeContext(self._version, sid=sid, ) + payload, status_code, headers = await self._fetch_async() + instance = SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 SupportingDocumentTypePage(Page): - """ """ - def __init__(self, version, response, solution): + def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentTypeInstance: + """ + Build an instance of SupportingDocumentTypeInstance + + :param payload: Payload response from the API """ - Initialize the SupportingDocumentTypePage - :param Version version: Version that contains the resource - :param Response response: Response from the API + return SupportingDocumentTypeInstance(self._version, payload) - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypePage - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypePage + def __repr__(self) -> str: """ - super(SupportingDocumentTypePage, self).__init__(version, response) + Provide a friendly representation - # Path Solution - self._solution = solution + :returns: Machine friendly representation + """ + return "" - def get_instance(self, payload): + +class SupportingDocumentTypeList(ListResource): + + def __init__(self, version: Version): """ - Build an instance of SupportingDocumentTypeInstance + Initialize the SupportingDocumentTypeList - :param dict payload: Payload response from the API + :param version: Version that contains the resource - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeInstance """ - return SupportingDocumentTypeInstance(self._version, payload, ) + super().__init__(version) + + self._uri = "/RegulatoryCompliance/SupportingDocumentTypes" - def __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SupportingDocumentTypeInstance]: """ - Provide a friendly representation + 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 """ - return '' + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + return self._version.stream(page, limits["limit"]) -class SupportingDocumentTypeContext(InstanceContext): - """ """ + 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) - def __init__(self, version, sid): + :returns: Generator that will yield up to limit results """ - Initialize the SupportingDocumentTypeContext + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the Supporting Document Type resource + return self._version.stream_async(page, limits["limit"]) - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeContext + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(SupportingDocumentTypeContext, self).__init__(version) + Streams SupportingDocumentTypeInstance and returns headers from first page - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RegulatoryCompliance/SupportingDocumentTypes/{sid}'.format(**self._solution) - 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: tuple of (generator, status_code, headers) where generator yields instances """ - Fetch the SupportingDocumentTypeInstance + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: The fetched SupportingDocumentTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeInstance + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronously streams SupportingDocumentTypeInstance and returns headers from first page + - return SupportingDocumentTypeInstance(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) - def __repr__(self): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Provide a friendly representation + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :returns: Machine friendly representation - :rtype: str + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentTypeInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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) -class SupportingDocumentTypeInstance(InstanceResource): - """ """ + :returns: list that will contain up to limit results + """ + + return 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. - 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 - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeInstance + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - super(SupportingDocumentTypeInstance, self).__init__(version) + Lists SupportingDocumentTypeInstance and returns headers from first page - # 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'), - } - # Context - self._context = None - self._solution = {'sid': sid or 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 _proxy(self): + :returns: ApiResponse with list of instances, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: SupportingDocumentTypeContext for this SupportingDocumentTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeContext + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - if self._context is None: - self._context = SupportingDocumentTypeContext(self._version, sid=self._solution['sid'], ) - return self._context + Asynchronously lists SupportingDocumentTypeInstance and returns headers from first page - @property - def 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: ApiResponse with list of instances, status code, and headers """ - :returns: The unique string that identifies the Supporting Document Type resource - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['sid'] + Retrieve a single page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately - @property - def friendly_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 SupportingDocumentTypeInstance """ - :returns: A human-readable description of the Supporting Document Type 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 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: """ - return self._properties['friendly_name'] + Asynchronously retrieve a single page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately - @property - def machine_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 SupportingDocumentTypeInstance """ - :returns: The machine-readable description of the Supporting Document Type 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 SupportingDocumentTypePage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['machine_name'] + Retrieve a single page with response metadata - @property - def fields(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: ApiResponse with SupportingDocumentTypePage, status code, and headers """ - :returns: The required information for creating a Supporting Document - :rtype: dict + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SupportingDocumentTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['fields'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with SupportingDocumentTypePage, status code, and headers """ - :returns: The absolute URL of the Supporting Document Type 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SupportingDocumentTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> SupportingDocumentTypePage: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of SupportingDocumentTypeInstance """ - Fetch the SupportingDocumentTypeInstance + response = self._version.domain.twilio.request("GET", target_url) + return SupportingDocumentTypePage(self._version, response) - :returns: The fetched SupportingDocumentTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeInstance + async def get_page_async(self, target_url: str) -> SupportingDocumentTypePage: """ - return self._proxy.fetch() + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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/v3/__init__.py b/twilio/rest/numbers/v3/__init__.py new file mode 100644 index 0000000000..9826e176fb --- /dev/null +++ b/twilio/rest/numbers/v3/__init__.py @@ -0,0 +1,43 @@ +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.v3.hosted_number_order import HostedNumberOrderList + + +class V3(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V3 version of Numbers + + :param domain: The Twilio.numbers domain + """ + super().__init__(domain, "v3") + self._hosted_number_orders: Optional[HostedNumberOrderList] = None + + @property + def hosted_number_orders(self) -> HostedNumberOrderList: + if self._hosted_number_orders is None: + self._hosted_number_orders = HostedNumberOrderList(self) + return self._hosted_number_orders + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v3/hosted_number_order.py b/twilio/rest/numbers/v3/hosted_number_order.py new file mode 100644 index 0000000000..bce747ff13 --- /dev/null +++ b/twilio/rest/numbers/v3/hosted_number_order.py @@ -0,0 +1,529 @@ +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 __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +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" + PHONE_BILL = "phone-bill" + + """ + :ivar sid: A 34 character string that uniquely identifies this HostedNumberOrder. + :ivar account_sid: A 34 character string that uniquely identifies the account. + :ivar incoming_phone_number_sid: A 34 character string that uniquely identifies the [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the phone number being hosted. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :ivar signing_document_sid: A 34 character string that uniquely identifies the [Authorization Document](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource) the user needs to sign. + :ivar phone_number: Phone number to be hosted. This must be in [E.164](https://en.wikipedia.org/wiki/E.164) format, e.g., +16175551212 + :ivar capabilities: + :ivar friendly_name: A 64 character string that is a human-readable text that describes this resource. + :ivar unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :ivar status: + :ivar failure_reason: A message that explains why a hosted_number_order went to status \"action-required\" + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar verification_attempts: The number of attempts made to verify ownership of the phone number that is being hosted. + :ivar email: Email of the owner of this phone number that is being hosted. + :ivar cc_emails: A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :ivar url: The URL of this HostedNumberOrder. + :ivar verification_type: + :ivar verification_document_sid: A 34 character string that uniquely identifies the Identity Document resource that represents the document for verifying ownership of the number to be hosted. + :ivar extension: A numerical extension to be used when making the ownership verification call. + :ivar call_delay: A value between 0-30 specifying the number of seconds to delay initiating the ownership verification call. + :ivar verification_code: A verification code provided in the response for a user to enter when they pick up the phone call. + :ivar verification_call_sids: A list of 34 character strings that are unique identifiers for the calls placed as part of ownership verification. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("accountSid") + self.incoming_phone_number_sid: Optional[str] = payload.get( + "incomingPhoneNumberSid" + ) + self.address_sid: Optional[str] = payload.get("addressSid") + self.signing_document_sid: Optional[str] = payload.get("signingDocumentSid") + self.phone_number: Optional[str] = payload.get("phoneNumber") + self.capabilities: Optional[str] = payload.get("capabilities") + self.friendly_name: Optional[str] = payload.get("friendlyName") + self.unique_name: Optional[str] = payload.get("uniqueName") + self.status: Optional["HostedNumberOrderInstance.Status"] = payload.get( + "status" + ) + self.failure_reason: Optional[str] = payload.get("failureReason") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateCreated") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateUpdated") + ) + self.verification_attempts: Optional[int] = deserialize.integer( + payload.get("verificationAttempts") + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("ccEmails") + self.url: Optional[str] = payload.get("url") + self.verification_type: Optional[ + "HostedNumberOrderInstance.VerificationType" + ] = payload.get("verificationType") + self.verification_document_sid: Optional[str] = payload.get( + "verificationDocumentSid" + ) + self.extension: Optional[str] = payload.get("extension") + self.call_delay: Optional[int] = deserialize.integer(payload.get("callDelay")) + self.verification_code: Optional[str] = payload.get("verificationCode") + self.verification_call_sids: Optional[List[str]] = payload.get( + "verificationCallSids" + ) + + 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 = "/HostedNumbers/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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Create the HostedNumberOrderInstance + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Optional. Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + + :returns: The created HostedNumberOrderInstance + """ + payload, _, _ = self._create( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + return HostedNumberOrderInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the HostedNumberOrderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + instance = HostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + return HostedNumberOrderInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the HostedNumberOrderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + instance = HostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/oauth/OauthBase.py b/twilio/rest/oauth/OauthBase.py new file mode 100644 index 0000000000..b26f459963 --- /dev/null +++ b/twilio/rest/oauth/OauthBase.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.oauth.v1 import V1 +from twilio.rest.oauth.v2 import V2 + + +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 + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Oauth + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Oauth + """ + 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/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..69ff398da9 --- /dev/null +++ b/twilio/rest/oauth/v1/authorize.py @@ -0,0 +1,221 @@ +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.api_response import ApiResponse + +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, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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, + } + ) + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers, params=params + ) + + 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: + """ + 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 + """ + payload, _, _ = self._fetch( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + return AuthorizeInstance(self._version, payload) + + def fetch_with_http_info( + 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, + ) -> ApiResponse: + """ + Fetch the AuthorizeInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + instance = AuthorizeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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, + } + ) + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + 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 + """ + payload, _, _ = await self._fetch_async( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + return AuthorizeInstance(self._version, payload) + + async def fetch_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously fetch the AuthorizeInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + instance = AuthorizeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..ebf53dc523 --- /dev/null +++ b/twilio/rest/oauth/v1/token.py @@ -0,0 +1,301 @@ +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.api_response import ApiResponse + +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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + 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, + ) + return TokenInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the TokenInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + 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, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + 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, + ) + return TokenInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the TokenInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + 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, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/oauth/v2/__init__.py b/twilio/rest/oauth/v2/__init__.py new file mode 100644 index 0000000000..c061f851c4 --- /dev/null +++ b/twilio/rest/oauth/v2/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + User OAuth API + User OAuth 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.v2.authorize import AuthorizeList +from twilio.rest.oauth.v2.token import TokenList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Oauth + + :param domain: The Twilio.oauth domain + """ + super().__init__(domain, "v2") + 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/v2/authorize.py b/twilio/rest/oauth/v2/authorize.py new file mode 100644 index 0000000000..53841e7188 --- /dev/null +++ b/twilio/rest/oauth/v2/authorize.py @@ -0,0 +1,221 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + User OAuth API + User OAuth API + + 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.api_response import ApiResponse + +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, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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, + } + ) + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers, params=params + ) + + 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: + """ + Fetch the AuthorizeInstance + + :param response_type: :param client_id: :param redirect_uri: :param scope: :param state: + :returns: The fetched AuthorizeInstance + """ + payload, _, _ = self._fetch( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + return AuthorizeInstance(self._version, payload) + + def fetch_with_http_info( + 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, + ) -> ApiResponse: + """ + Fetch the AuthorizeInstance and return response metadata + + :param response_type: :param client_id: :param redirect_uri: :param scope: :param state: + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + instance = AuthorizeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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, + } + ) + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + 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: :param client_id: :param redirect_uri: :param scope: :param state: + :returns: The fetched AuthorizeInstance + """ + payload, _, _ = await self._fetch_async( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + return AuthorizeInstance(self._version, payload) + + async def fetch_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously fetch the AuthorizeInstance and return response metadata + + :param response_type: :param client_id: :param redirect_uri: :param scope: :param state: + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + instance = AuthorizeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/oauth/v2/token.py b/twilio/rest/oauth/v2/token.py new file mode 100644 index 0000000000..3550e4b506 --- /dev/null +++ b/twilio/rest/oauth/v2/token.py @@ -0,0 +1,327 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + User OAuth API + User OAuth API + + 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.api_response import ApiResponse + +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, + account_sid: Union[str, object] = values.unset, + grant_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + params = values.of( + { + "account_sid": account_sid, + } + ) + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers, params=params + ) + + def create( + self, + account_sid: Union[str, object] = values.unset, + grant_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + 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 account_sid: Optional Account SID to perform on behalf of requests. + :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 + """ + payload, _, _ = self._create( + account_sid=account_sid, + 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, + ) + return TokenInstance(self._version, payload) + + def create_with_http_info( + self, + account_sid: Union[str, object] = values.unset, + grant_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + 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, + ) -> ApiResponse: + """ + Create the TokenInstance and return response metadata + + :param account_sid: Optional Account SID to perform on behalf of requests. + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + account_sid=account_sid, + 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, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + account_sid: Union[str, object] = values.unset, + grant_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + params = values.of( + { + "account_sid": account_sid, + } + ) + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers, params=params + ) + + async def create_async( + self, + account_sid: Union[str, object] = values.unset, + grant_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + 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 account_sid: Optional Account SID to perform on behalf of requests. + :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 + """ + payload, _, _ = await self._create_async( + account_sid=account_sid, + 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, + ) + return TokenInstance(self._version, payload) + + async def create_with_http_info_async( + self, + account_sid: Union[str, object] = values.unset, + grant_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + 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, + ) -> ApiResponse: + """ + Asynchronously create the TokenInstance and return response metadata + + :param account_sid: Optional Account SID to perform on behalf of requests. + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + account_sid=account_sid, + 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, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 35d6a7c998..c4658c62e3 100644 --- a/twilio/rest/preview/__init__.py +++ b/twilio/rest/preview/__init__.py @@ -1,249 +1,78 @@ -# 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.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 +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.wireless.command import CommandList +from twilio.rest.preview.wireless.rate_plan import RatePlanList +from twilio.rest.preview.wireless.sim import SimList -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 +class Preview(PreviewBase): @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 - """ + 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 - """ - 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 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 b3c9286de0..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'], limits['page_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 9118b3f151..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'], limits['page_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 09723b81c4..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists FleetInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.deployed_devices.fleet.FleetInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of FleetInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of FleetInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetPage - """ - 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 e82941e6d6..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'], limits['page_limit']) - - def list(self, device_sid=values.unset, limit=None, page_size=None): - """ - Lists CertificateInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode device_sid: Find all Certificates authenticating specified Device. - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance] - """ - return list(self.stream(device_sid=device_sid, limit=limit, page_size=page_size, )) - - def page(self, device_sid=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of CertificateInstance records from the API. - Request is executed immediately - - :param unicode device_sid: Find all Certificates authenticating specified Device. - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of CertificateInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificatePage - """ - 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 d4ae7874da..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists DeploymentInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of DeploymentInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of DeploymentInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentPage - """ - 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 7a14eacbd7..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'], limits['page_limit']) - - def list(self, deployment_sid=values.unset, limit=None, page_size=None): - """ - Lists DeviceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode deployment_sid: Find all Devices grouped under the specified Deployment. - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance] - """ - return list(self.stream(deployment_sid=deployment_sid, limit=limit, page_size=page_size, )) - - def page(self, deployment_sid=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of DeviceInstance records from the API. - Request is executed immediately - - :param unicode deployment_sid: Find all Devices grouped under the specified Deployment. - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of DeviceInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DevicePage - """ - 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 21443984c8..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'], limits['page_limit']) - - def list(self, device_sid=values.unset, limit=None, page_size=None): - """ - Lists KeyInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode device_sid: Find all Keys authenticating specified Device. - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.deployed_devices.fleet.key.KeyInstance] - """ - return list(self.stream(device_sid=device_sid, limit=limit, page_size=page_size, )) - - def page(self, device_sid=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of KeyInstance records from the API. - Request is executed immediately - - :param unicode device_sid: Find all Keys authenticating specified Device. - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of KeyInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyPage - """ - 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 de099787af..27ff55c37d 100644 --- a/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py +++ b/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py @@ -1,502 +1,1330 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +class AuthorizationDocumentInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the AuthorizationDocumentList + class Status(object): + OPENED = "opened" + SIGNING = "signing" + SIGNED = "signed" + CANCELED = "canceled" + FAILED = "failed" - :param Version version: Version that contains the resource + """ + :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") - :returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentList - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentList - """ - super(AuthorizationDocumentList, self).__init__(version) + self._solution = { + "sid": sid or self.sid, + } - # Path Solution - self._solution = {} - self._uri = '/AuthorizationDocuments'.format(**self._solution) + 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. + 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 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) + :returns: AuthorizationDocumentContext for this AuthorizationDocumentInstance + """ + if self._context is None: + self._context = AuthorizationDocumentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance] + def fetch(self) -> "AuthorizationDocumentInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the AuthorizationDocumentInstance - page = self.page(email=email, status=status, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched AuthorizationDocumentInstance + """ + return self._proxy.fetch() - def list(self, email=values.unset, status=values.unset, limit=None, - page_size=None): + async def fetch_async(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. + Asynchronous coroutine to 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 await self._proxy.fetch_async() - def page(self, email=values.unset, status=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of AuthorizationDocumentInstance records from the API. - Request is executed immediately + Fetch the AuthorizationDocumentInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Email': email, - 'Status': status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance with HTTP info - return AuthorizationDocumentPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of AuthorizationDocumentInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> "AuthorizationDocumentInstance": + """ + Update the AuthorizationDocumentInstance - :returns: Page of AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentPage + :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 """ - 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 + 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, + ) - :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. + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the AuthorizationDocumentInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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 - """ - 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), - }) + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AuthorizationDocumentInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + @property + def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: + """ + Access the dependent_hosted_number_orders + """ + return self._proxy.dependent_hosted_number_orders - return AuthorizationDocumentInstance(self._version, payload, ) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(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 +class AuthorizationDocumentContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - return AuthorizationDocumentContext(self._version, sid=sid, ) + Initialize the AuthorizationDocumentContext - def __call__(self, sid): + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. """ - Constructs a AuthorizationDocumentContext + super().__init__(version) - :param sid: AuthorizationDocument sid. + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/AuthorizationDocuments/{sid}".format(**self._solution) - :returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext - """ - return AuthorizationDocumentContext(self._version, sid=sid, ) + self._dependent_hosted_number_orders: Optional[ + DependentHostedNumberOrderList + ] = None - def __repr__(self): + def _fetch(self) -> tuple: """ - Provide a friendly representation + Internal helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -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. """ + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - 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 + payload, _, _ = self._fetch() + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def get_instance(self, payload): + def fetch_with_http_info(self) -> ApiResponse: """ - Build an instance of AuthorizationDocumentInstance + Fetch the AuthorizationDocumentInstance and return response metadata - :param dict payload: Payload response from the API - :returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance + :returns: ApiResponse with instance, status code, and headers """ - return AuthorizationDocumentInstance(self._version, payload, ) + payload, status_code, headers = self._fetch() + instance = AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + async def fetch_async(self) -> AuthorizationDocumentInstance: """ - Initialize the AuthorizationDocumentContext + Asynchronous coroutine to fetch the AuthorizationDocumentInstance - :param Version version: Version that contains the resource - :param sid: AuthorizationDocument sid. - :returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext + :returns: The fetched AuthorizationDocumentInstance """ - super(AuthorizationDocumentContext, self).__init__(version) + payload, _, _ = await self._fetch_async() + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/AuthorizationDocuments/{sid}'.format(**self._solution) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance and return response metadata - # Dependents - self._dependent_hosted_number_orders = None - def fetch(self): + :returns: ApiResponse with instance, status code, and headers """ - Fetch the AuthorizationDocumentInstance + payload, status_code, headers = await self._fetch_async() + instance = AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "HostedNumberOrderSids": serialize.map( + hosted_number_order_sids, lambda e: e + ), + "AddressSid": address_sid, + "Email": email, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "Status": status, + "ContactTitle": contact_title, + "ContactPhoneNumber": contact_phone_number, + } + ) + headers = values.of({}) - :returns: The fetched AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - return AuthorizationDocumentInstance(self._version, payload, sid=self._solution['sid'], ) + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - 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): + def update( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> AuthorizationDocumentInstance: """ Update the AuthorizationDocumentInstance - :param unicode hosted_number_order_sids: A list of HostedNumberOrder sids. - :param unicode address_sid: Address sid. - :param unicode email: Email. - :param unicode cc_emails: A list of emails. - :param AuthorizationDocumentInstance.Status status: The Status of this AuthorizationDocument. - :param unicode contact_title: Title of signee of this Authorization Document. - :param unicode contact_phone_number: Authorization Document's signee's phone number. + :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._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 AuthorizationDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the AuthorizationDocumentInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = AuthorizationDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" - return AuthorizationDocumentInstance(self._version, payload, sid=self._solution['sid'], ) + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + cc_emails=cc_emails, + status=status, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + ) + return AuthorizationDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AuthorizationDocumentInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = AuthorizationDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 Status(object): - OPENED = "opened" - SIGNING = "signing" - SIGNED = "signed" - CANCELED = "canceled" - FAILED = "failed" +class AuthorizationDocumentPage(Page): - def __init__(self, version, payload, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> AuthorizationDocumentInstance: """ - Initialize the AuthorizationDocumentInstance + Build an instance of AuthorizationDocumentInstance - :returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance + :param payload: Payload response from the API """ - super(AuthorizationDocumentInstance, self).__init__(version) - - # 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'), - } - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + return AuthorizationDocumentInstance(self._version, payload) - @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: AuthorizationDocumentContext for this AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext + :returns: Machine friendly representation """ - if self._context is None: - self._context = AuthorizationDocumentContext(self._version, sid=self._solution['sid'], ) - return self._context + return "" - @property - def sid(self): + +class AuthorizationDocumentList(ListResource): + + def __init__(self, version: Version): """ - :returns: AuthorizationDocument sid. - :rtype: unicode + Initialize the AuthorizationDocumentList + + :param version: Version that contains the resource + """ - return self._properties['sid'] + super().__init__(version) - @property - def address_sid(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, + ) -> tuple: """ - :returns: Address sid. - :rtype: unicode + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['address_sid'] - @property - def status(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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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'] + payload, _, _ = self._create( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + cc_emails=cc_emails, + ) + return AuthorizationDocumentInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the AuthorizationDocumentInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + cc_emails=cc_emails, + ) + instance = AuthorizationDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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"}) - @property - def email(self): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + hosted_number_order_sids: List[str], + address_sid: str, + email: str, + contact_title: str, + contact_phone_number: str, + cc_emails: Union[List[str], object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Asynchronously create the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: The created AuthorizationDocumentInstance """ - :returns: Email. - :rtype: unicode + payload, _, _ = await self._create_async( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + cc_emails=cc_emails, + ) + return AuthorizationDocumentInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the AuthorizationDocumentInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + cc_emails=cc_emails, + ) + instance = AuthorizationDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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]: """ - return self._properties['email'] + 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. - @property - def cc_emails(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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: A list of emails. - :rtype: unicode + 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]: """ - return self._properties['cc_emails'] + 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. - @property - def date_created(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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 AuthorizationDocument was created. - :rtype: datetime + 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 stream_with_http_info( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_created'] + Streams AuthorizationDocumentInstance and returns headers from first page - @property - def date_updated(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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The date this AuthorizationDocument was updated. - :rtype: datetime + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + email=email, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_updated'] + Asynchronously streams AuthorizationDocumentInstance and returns headers from first page - @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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The url - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + email=email, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - return self._properties['url'] + 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 links(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 """ - :returns: The links - :rtype: unicode + + 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['links'] + 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. - def fetch(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 list_with_http_info( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Fetch the AuthorizationDocumentInstance + Lists AuthorizationDocumentInstance and returns headers from first page - :returns: The fetched AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance + + :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: ApiResponse with list of instances, status code, and headers """ - return self._proxy.fetch() + generator, status_code, headers = self.stream_with_http_info( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - 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): + async def list_with_http_info_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Update the AuthorizationDocumentInstance + Asynchronously lists AuthorizationDocumentInstance and returns headers from first page - :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. - :returns: The updated AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance + :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: ApiResponse with list of instances, status code, and headers """ - return self._proxy.update( - hosted_number_order_sids=hosted_number_order_sids, - address_sid=address_sid, + generator, status_code, headers = await self.stream_with_http_info_async( email=email, - cc_emails=cc_emails, status=status, - contact_title=contact_title, - contact_phone_number=contact_phone_number, + limit=limit, + page_size=page_size, ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 - @property - def dependent_hosted_number_orders(self): + :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 """ - Access the dependent_hosted_number_orders + 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" - :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 + 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 """ - return self._proxy.dependent_hosted_number_orders + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with AuthorizationDocumentPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AuthorizationDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with AuthorizationDocumentPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AuthorizationDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 66c2f91e4e..1d52db3b65 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,768 @@ -# 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.api_response import ApiResponse + from twilio.base.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): + 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" + PHONE_BILL = "phone-bill" + + """ + :ivar sid: A 34 character string that uniquely identifies this Authorization Document + :ivar account_sid: The unique SID identifier of the Account. + :ivar incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :ivar signing_document_sid: A 34 character string that uniquely identifies the LOA document associated with this HostedNumberOrder. + :ivar phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :ivar capabilities: + :ivar friendly_name: A human readable description of this resource, up to 64 characters. + :ivar unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :ivar status: + :ivar failure_reason: A message that explains why a hosted_number_order went to status \"action-required\" + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar verification_attempts: The number of attempts made to verify ownership of the phone number that is being hosted. + :ivar email: Email of the owner of this phone number that is being hosted. + :ivar cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :ivar verification_type: + :ivar verification_document_sid: A 34 character string that uniquely identifies the Identity Document resource that represents the document for verifying ownership of the number to be hosted. + :ivar extension: A numerical extension to be used when making the ownership verification call. + :ivar call_delay: A value between 0-30 specifying the number of seconds to delay initiating the ownership verification call. + :ivar verification_code: The digits passed during the ownership verification call. + :ivar verification_call_sids: A list of 34 character strings that are unique identifiers for the calls placed as part of ownership verification. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], signing_document_sid: str + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.incoming_phone_number_sid: Optional[str] = payload.get( + "incoming_phone_number_sid" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.signing_document_sid: Optional[str] = payload.get("signing_document_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.capabilities: Optional[str] = payload.get("capabilities") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.status: Optional["DependentHostedNumberOrderInstance.Status"] = ( + payload.get("status") + ) + self.failure_reason: Optional[str] = payload.get("failure_reason") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.verification_attempts: Optional[int] = deserialize.integer( + payload.get("verification_attempts") + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.verification_type: Optional[ + "DependentHostedNumberOrderInstance.VerificationType" + ] = payload.get("verification_type") + self.verification_document_sid: Optional[str] = payload.get( + "verification_document_sid" + ) + self.extension: Optional[str] = payload.get("extension") + self.call_delay: Optional[int] = deserialize.integer(payload.get("call_delay")) + self.verification_code: Optional[str] = payload.get("verification_code") + self.verification_call_sids: Optional[List[str]] = payload.get( + "verification_call_sids" + ) + + self._solution = { + "signing_document_sid": signing_document_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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): - """ PLEASE NOTE that this class contains preview products that are subject - 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): + def __init__(self, version: Version, signing_document_sid: str): """ Initialize the DependentHostedNumberOrderList - :param Version version: Version that contains the resource - :param signing_document_sid: LOA document sid. + :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. - :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) + super().__init__(version) # Path Solution - self._solution = {'signing_document_sid': signing_document_sid, } - self._uri = '/AuthorizationDocuments/{signing_document_sid}/DependentHostedNumberOrders'.format(**self._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): + def stream( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DependentHostedNumberOrderInstance]: """ Streams DependentHostedNumberOrderInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param DependentHostedNumberOrderInstance.Status status: 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) + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance] """ 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'], + page_size=limits["page_size"], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, status=values.unset, phone_number=values.unset, - incoming_phone_number_sid=values.unset, friendly_name=values.unset, - unique_name=values.unset, limit=None, page_size=None): - """ - Lists DependentHostedNumberOrderInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DependentHostedNumberOrderInstance]: + """ + Asynchronously streams DependentHostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :param DependentHostedNumberOrderInstance.Status status: 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) + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance] """ - return list(self.stream( + 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, - limit=limit, - page_size=page_size, - )) + page_size=limits["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): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Retrieve a single page of DependentHostedNumberOrderInstance records from the API. - Request is executed immediately + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) - :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 + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) - :returns: Page of DependentHostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderPage + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - 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, - }) + Lists DependentHostedNumberOrderInstance 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 "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, + ) + ) - return DependentHostedNumberOrderPage(self._version, response, self._solution) + 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. - def get_page(self, target_url): + :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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists DependentHostedNumberOrderInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists DependentHostedNumberOrderInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DependentHostedNumberOrderPage: """ - Retrieve a specific page of DependentHostedNumberOrderInstance records from the API. + Retrieve a single page of DependentHostedNumberOrderInstance records from the API. Request is executed immediately - :param str target_url: API-generated URL for the requested results page + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 :returns: Page of DependentHostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderPage """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, + } ) - return DependentHostedNumberOrderPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -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) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Path Solution - self._solution = solution + headers["Accept"] = "application/json" - def get_instance(self, payload): - """ - 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 - """ - return DependentHostedNumberOrderInstance( - self._version, - payload, - signing_document_sid=self._solution['signing_document_sid'], + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - 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 Status(object): - RECEIVED = "received" - PENDING_VERIFICATION = "pending-verification" - VERIFIED = "verified" - PENDING_LOA = "pending-loa" - CARRIER_PROCESSING = "carrier-processing" - TESTING = "testing" - COMPLETED = "completed" - FAILED = "failed" - ACTION_REQUIRED = "action-required" - - class VerificationType(object): - PHONE_CALL = "phone-call" - PHONE_BILL = "phone-bill" - - def __init__(self, version, payload, signing_document_sid): - """ - Initialize the DependentHostedNumberOrderInstance - - :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'), - } - - # Context - self._context = None - self._solution = {'signing_document_sid': signing_document_sid, } - - @property - def sid(self): - """ - :returns: HostedNumberOrder sid. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: Account sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @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'] + 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 signing_document_sid(self): - """ - :returns: LOA document sid. - :rtype: unicode - """ - return self._properties['signing_document_sid'] + :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 phone_number(self): - """ - :returns: An E164 formatted phone number. - :rtype: unicode + :returns: Page of DependentHostedNumberOrderInstance """ - return self._properties['phone_number'] + 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 capabilities(self): - """ - :returns: A mapping of phone number capabilities. - :rtype: unicode - """ - return self._properties['capabilities'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def friendly_name(self): - """ - :returns: A human readable description of this resource. - :rtype: unicode - """ - return self._properties['friendly_name'] + headers["Accept"] = "application/json" - @property - def unique_name(self): - """ - :returns: A unique, developer assigned name of this HostedNumberOrder. - :rtype: unicode - """ - return self._properties['unique_name'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) - @property - def status(self): - """ - :returns: The Status of this HostedNumberOrder. - :rtype: DependentHostedNumberOrderInstance.Status - """ - return self._properties['status'] + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DependentHostedNumberOrderPage, status code, and headers + """ + 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 failure_reason(self): - """ - :returns: Why a hosted_number_order reached status "action-required" - :rtype: unicode - """ - return self._properties['failure_reason'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_created(self): - """ - :returns: The date this HostedNumberOrder was created. - :rtype: datetime - """ - return self._properties['date_created'] + headers["Accept"] = "application/json" - @property - def date_updated(self): - """ - :returns: The date this HostedNumberOrder was updated. - :rtype: datetime - """ - return self._properties['date_updated'] + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DependentHostedNumberOrderPage, status code, and headers + """ + 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_attempts(self): - """ - :returns: The number of attempts made to verify ownership of the phone number. - :rtype: unicode - """ - return self._properties['verification_attempts'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def email(self): - """ - :returns: Email. - :rtype: unicode - """ - return self._properties['email'] + headers["Accept"] = "application/json" - @property - def cc_emails(self): - """ - :returns: A list of emails. - :rtype: unicode - """ - return self._properties['cc_emails'] + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def verification_type(self): - """ - :returns: The method used for verifying ownership of the number to be hosted. - :rtype: DependentHostedNumberOrderInstance.VerificationType + def get_page(self, target_url: str) -> DependentHostedNumberOrderPage: """ - return self._properties['verification_type'] + Retrieve a specific page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately - @property - def verification_document_sid(self): - """ - :returns: Verification Document Sid. - :rtype: unicode - """ - return self._properties['verification_document_sid'] + :param target_url: API-generated URL for the requested results page - @property - def extension(self): - """ - :returns: Phone extension to use for ownership verification call. - :rtype: unicode + :returns: Page of DependentHostedNumberOrderInstance """ - return self._properties['extension'] + response = self._version.domain.twilio.request("GET", target_url) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) - @property - def call_delay(self): + async def get_page_async(self, target_url: str) -> DependentHostedNumberOrderPage: """ - :returns: Seconds (0-30) to delay ownership verification call by. - :rtype: unicode - """ - return self._properties['call_delay'] + Asynchronously retrieve a specific page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately - @property - def verification_code(self): - """ - :returns: The digits passed during the ownership verification call. - :rtype: unicode - """ - return self._properties['verification_code'] + :param target_url: API-generated URL for the requested results page - @property - def verification_call_sids(self): - """ - :returns: List of IDs for ownership verification calls. - :rtype: unicode + :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, solution=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 f256e42581..1b26c1b53b 100644 --- a/twilio/rest/preview/hosted_numbers/hosted_number_order.py +++ b/twilio/rest/preview/hosted_numbers/hosted_number_order.py @@ -1,699 +1,1857 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + 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" - :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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :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) + :returns: HostedNumberOrderContext for this HostedNumberOrderInstance + """ + if self._context is None: + self._context = HostedNumberOrderContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the HostedNumberOrderInstance - page = self.page( - status=status, - phone_number=phone_number, - incoming_phone_number_sid=incoming_phone_number_sid, - friendly_name=friendly_name, - unique_name=unique_name, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - 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): + async def delete_async(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. + 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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 await self._proxy.delete_async() - 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): + def delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of HostedNumberOrderInstance records from the API. - Request is executed immediately + Deletes the HostedNumberOrderInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - 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, - }) + return self._proxy.delete_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance with HTTP info - return HostedNumberOrderPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with success boolean, status code, and headers """ - Retrieve a specific page of HostedNumberOrderInstance records from the API. - Request is executed immediately + return await self._proxy.delete_with_http_info_async() - :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 + def fetch(self) -> "HostedNumberOrderInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Fetch the HostedNumberOrderInstance - return HostedNumberOrderPage(self._version, response, self._solution) - def create(self, phone_number, sms_capability, account_sid=values.unset, - friendly_name=values.unset, unique_name=values.unset, - cc_emails=values.unset, sms_url=values.unset, - sms_method=values.unset, sms_fallback_url=values.unset, - sms_fallback_method=values.unset, status_callback_url=values.unset, - status_callback_method=values.unset, - sms_application_sid=values.unset, address_sid=values.unset, - email=values.unset, verification_type=values.unset, - verification_document_sid=values.unset): + :returns: The fetched HostedNumberOrderInstance """ - Create 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 + return self._proxy.fetch() - :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): + async def fetch_async(self) -> "HostedNumberOrderInstance": """ - Constructs a HostedNumberOrderContext + Asynchronous coroutine to fetch the HostedNumberOrderInstance - :param sid: HostedNumberOrder sid. - :returns: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderContext - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderContext + :returns: The fetched HostedNumberOrderInstance """ - return HostedNumberOrderContext(self._version, sid=sid, ) + return await self._proxy.fetch_async() - def __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a HostedNumberOrderContext + Fetch the HostedNumberOrderInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return HostedNumberOrderContext(self._version, sid=sid, ) + return self._proxy.fetch_with_http_info() - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + async def fetch_with_http_info_async(self) -> ApiResponse: """ - return '' + Asynchronous coroutine to fetch the HostedNumberOrderInstance with HTTP info -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. """ + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() - def __init__(self, version, response, solution): + 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": """ - Initialize the HostedNumberOrderPage + Update the HostedNumberOrderInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API + :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.HostedNumberOrderPage - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderPage + :returns: The updated HostedNumberOrderInstance """ - super(HostedNumberOrderPage, self).__init__(version, response) + 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, + ) - # Path Solution - self._solution = solution + 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. - def get_instance(self, payload): + :returns: The updated HostedNumberOrderInstance """ - Build an instance of HostedNumberOrderInstance + return await self._proxy.update_async( + friendly_name=friendly_name, + unique_name=unique_name, + email=email, + cc_emails=cc_emails, + status=status, + verification_code=verification_code, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + extension=extension, + call_delay=call_delay, + ) - :param dict payload: Payload response from the API + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the HostedNumberOrderInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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, + ) - :returns: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance - """ - return HostedNumberOrderInstance(self._version, payload, ) + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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 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. """ - def __init__(self, version, sid): + def __init__(self, version: Version, sid: str): """ Initialize the HostedNumberOrderContext - :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 + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. """ - super(HostedNumberOrderContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'sid': sid, } - self._uri = '/HostedNumberOrders/{sid}'.format(**self._solution) + self._solution = { + "sid": sid, + } + self._uri = "/HostedNumberOrders/{sid}".format(**self._solution) - def fetch(self): + def _delete(self) -> tuple: """ - Fetch the HostedNumberOrderInstance + Internal helper for delete operation - :returns: The fetched HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return HostedNumberOrderInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) - def delete(self): + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ Deletes the HostedNumberOrderInstance + :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + success, _, _ = self._delete() + return success - 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 delete_with_http_info(self) -> ApiResponse: """ - Update the HostedNumberOrderInstance + Deletes the HostedNumberOrderInstance and return response metadata - :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. - :returns: The updated HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance + :returns: ApiResponse with success boolean, status code, and headers """ - 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, ) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - return HostedNumberOrderInstance(self._version, payload, sid=self._solution['sid'], ) - - def __repr__(self): + async def _delete_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for delete operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (success_boolean, status_code, headers) """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -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. """ - 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" + headers = values.of({}) - class VerificationType(object): - PHONE_CALL = "phone-call" - PHONE_BILL = "phone-bill" + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - 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'), - } + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): + :returns: True if delete succeeds, False otherwise """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + success, _, _ = await self._delete_async() + return success - :returns: HostedNumberOrderContext for this HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderContext + async def delete_with_http_info_async(self) -> ApiResponse: """ - if self._context is None: - self._context = HostedNumberOrderContext(self._version, sid=self._solution['sid'], ) - return self._context + Asynchronous coroutine that deletes the HostedNumberOrderInstance and return response metadata - @property - def sid(self): - """ - :returns: HostedNumberOrder sid. - :rtype: unicode - """ - return self._properties['sid'] - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode + :returns: ApiResponse with success boolean, status code, and headers """ - return self._properties['account_sid'] + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - @property - def incoming_phone_number_sid(self): - """ - :returns: IncomingPhoneNumber sid. - :rtype: unicode + def _fetch(self) -> tuple: """ - return self._properties['incoming_phone_number_sid'] + Internal helper for fetch operation - @property - def address_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: Address sid. - :rtype: unicode - """ - return self._properties['address_sid'] - @property - def signing_document_sid(self): - """ - :returns: LOA document sid. - :rtype: unicode - """ - return self._properties['signing_document_sid'] + headers = values.of({}) - @property - def phone_number(self): + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> HostedNumberOrderInstance: """ - :returns: An E164 formatted phone number. - :rtype: unicode + Fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance """ - return self._properties['phone_number'] + payload, _, _ = self._fetch() + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - @property - def capabilities(self): + def fetch_with_http_info(self) -> ApiResponse: """ - :returns: A mapping of phone number capabilities. - :rtype: unicode + Fetch the HostedNumberOrderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['capabilities'] + payload, status_code, headers = self._fetch() + instance = HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def friendly_name(self): + async def _fetch_async(self) -> tuple: """ - :returns: A human readable description of this resource. - :rtype: unicode + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['friendly_name'] - @property - def unique_name(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> HostedNumberOrderInstance: """ - :returns: A unique, developer assigned name of this HostedNumberOrder. - :rtype: unicode + Asynchronous coroutine to fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance """ - return self._properties['unique_name'] + payload, _, _ = await self._fetch_async() + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - @property - def status(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: The Status of this HostedNumberOrder. - :rtype: HostedNumberOrderInstance.Status + Asynchronous coroutine to fetch the HostedNumberOrderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['status'] + payload, status_code, headers = await self._fetch_async() + instance = HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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({}) - @property - def failure_reason(self): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - :returns: Why a hosted_number_order reached status "action-required" - :rtype: unicode + Update the HostedNumberOrderInstance + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: The updated HostedNumberOrderInstance """ - return self._properties['failure_reason'] + payload, _, _ = self._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 HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) - @property - def date_created(self): + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the HostedNumberOrderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Email": email, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "Status": status, + "VerificationCode": verification_code, + "VerificationType": verification_type, + "VerificationDocumentSid": verification_document_sid, + "Extension": extension, + "CallDelay": call_delay, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: The updated HostedNumberOrderInstance """ - :returns: The date this HostedNumberOrder was created. - :rtype: datetime + payload, _, _ = await self._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, + ) + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - return self._properties['date_created'] + Provide a friendly representation - @property - def date_updated(self): + :returns: Machine friendly representation """ - :returns: The date this HostedNumberOrder was updated. - :rtype: datetime + 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: """ - return self._properties['date_updated'] + Build an instance of HostedNumberOrderInstance - @property - def verification_attempts(self): + :param payload: Payload response from the API """ - :returns: The number of attempts made to verify ownership of the phone number. - :rtype: unicode + + return HostedNumberOrderInstance(self._version, payload) + + def __repr__(self) -> str: """ - return self._properties['verification_attempts'] + Provide a friendly representation - @property - def email(self): + :returns: Machine friendly representation """ - :returns: Email. - :rtype: unicode + return "" + + +class HostedNumberOrderList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['email'] + Initialize the HostedNumberOrderList - @property - def cc_emails(self): + :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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - :returns: A list of emails. - :rtype: unicode + 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 """ - return self._properties['cc_emails'] + payload, _, _ = self._create( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + return HostedNumberOrderInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the HostedNumberOrderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + instance = HostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 url(self): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: The URL of this HostedNumberOrder. - :rtype: unicode + payload, _, _ = await self._create_async( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + return HostedNumberOrderInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the HostedNumberOrderInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + instance = HostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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['url'] + 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 verification_type(self): - """ - :returns: The method used for verifying ownership of the number to be hosted. - :rtype: HostedNumberOrderInstance.VerificationType + :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 """ - return self._properties['verification_type'] + 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 verification_document_sid(self): + 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]: """ - :returns: Verification Document Sid. - :rtype: unicode + Asynchronously streams HostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['verification_document_sid'] + 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 extension(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: """ - :returns: Phone extension to use for ownership verification call. - :rtype: unicode + Streams HostedNumberOrderInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['extension'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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 call_delay(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams HostedNumberOrderInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: Seconds (0-30) to delay ownership verification call by. - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists HostedNumberOrderInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists HostedNumberOrderInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with HostedNumberOrderPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = HostedNumberOrderPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with HostedNumberOrderPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = HostedNumberOrderPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 + + :param target_url: API-generated URL for the requested results page - def fetch(self): + :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 87fdd95e64..76fc06a367 100644 --- a/twilio/rest/preview/marketplace/available_add_on/__init__.py +++ b/twilio/rest/preview/marketplace/available_add_on/__init__.py @@ -1,373 +1,679 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +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 - def __init__(self, version): + @property + def _proxy(self) -> "AvailableAddOnContext": """ - Initialize the AvailableAddOnList + 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: AvailableAddOnContext for this AvailableAddOnInstance + """ + if self._context is None: + self._context = AvailableAddOnContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnList - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnList + def fetch(self) -> "AvailableAddOnInstance": """ - super(AvailableAddOnList, self).__init__(version) + Fetch the AvailableAddOnInstance - # Path Solution - self._solution = {} - self._uri = '/AvailableAddOns'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "AvailableAddOnInstance": + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance - :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 await self._proxy.fetch_async() - page = self.page(page_size=limits['page_size'], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with instance, status code, and headers """ - 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 self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance with HTTP info - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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: ApiResponse with instance, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + @property + def extensions(self) -> AvailableAddOnExtensionList: """ - Retrieve a single page of AvailableAddOnInstance records from the API. - Request is executed immediately + Access the extensions + """ + return self._proxy.extensions - :param str page_token: PageToken provided by the API - :param 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 AvailableAddOnInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnPage + :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 AvailableAddOnPage(self._version, response, self._solution) +class AvailableAddOnContext(InstanceContext): - def get_page(self, target_url): + def __init__(self, version: Version, sid: str): """ - Retrieve a specific page of AvailableAddOnInstance records from the API. - Request is executed immediately + Initialize the AvailableAddOnContext - :param str target_url: API-generated URL for the requested results page + :param version: Version that contains the resource + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + super().__init__(version) - :returns: Page of AvailableAddOnInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnPage + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/AvailableAddOns/{sid}".format(**self._solution) + + self._extensions: Optional[AvailableAddOnExtensionList] = None + + def _fetch(self) -> tuple: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) - return AvailableAddOnPage(self._version, response, self._solution) + def fetch(self) -> AvailableAddOnInstance: + """ + Fetch the AvailableAddOnInstance - def get(self, sid): + + :returns: The fetched AvailableAddOnInstance """ - Constructs a AvailableAddOnContext + payload, _, _ = self._fetch() + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return AvailableAddOnContext(self._version, sid=sid, ) + payload, status_code, headers = self._fetch() + instance = AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __call__(self, sid): + async def _fetch_async(self) -> tuple: """ - Constructs a AvailableAddOnContext + Internal async helper for fetch operation - :param sid: The SID of the AvailableAddOn resource to fetch + Returns: + tuple: (payload, status_code, headers) + """ - :returns: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnContext - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnContext + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AvailableAddOnInstance: """ - return AvailableAddOnContext(self._version, sid=sid, ) + Asynchronous coroutine to fetch the AvailableAddOnInstance - def __repr__(self): + + :returns: The fetched AvailableAddOnInstance """ - Provide a friendly representation + payload, _, _ = await self._fetch_async() + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: Machine friendly representation - :rtype: str + async def fetch_with_http_info_async(self) -> ApiResponse: """ - return '' + Asynchronous coroutine to fetch the AvailableAddOnInstance and return response metadata -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. """ + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __init__(self, version, response, solution): + @property + def extensions(self) -> AvailableAddOnExtensionList: """ - Initialize the AvailableAddOnPage + Access the extensions + """ + 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, ) - def __repr__(self): + return AvailableAddOnInstance(self._version, payload) + + 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" + + 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. - # Dependents - self._extensions = None + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def fetch(self): + :returns: Generator that will yield up to limit results """ - Fetch 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - if self._extensions is None: - self._extensions = AvailableAddOnExtensionList( - self._version, - available_add_on_sid=self._solution['sid'], - ) - return self._extensions + Streams AvailableAddOnInstance and returns headers from first page - 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: tuple of (generator, status_code, headers) where generator yields instances """ - Provide a friendly representation + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: Machine friendly representation - :rtype: str + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Asynchronously streams AvailableAddOnInstance and returns headers from first page -class AvailableAddOnInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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, sid=None): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Initialize the AvailableAddOnInstance + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :returns: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnInstance + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnInstance]: """ - super(AvailableAddOnInstance, self).__init__(version) + Lists AvailableAddOnInstance 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'), - 'description': payload.get('description'), - 'pricing_type': payload.get('pricing_type'), - 'configuration_schema': payload.get('configuration_schema'), - '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 = {'sid': sid or self._properties['sid'], } + :returns: list that will contain up to limit results + """ - @property - def _proxy(self): + return 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]: """ - 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 AvailableAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: AvailableAddOnContext for this AvailableAddOnInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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 = AvailableAddOnContext(self._version, sid=self._solution['sid'], ) - return self._context - @property - def sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Lists AvailableAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def friendly_name(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Asynchronously lists AvailableAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['friendly_name'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def description(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, + ) -> 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 """ - :returns: A short description of the Add-on's functionality - :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 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: """ - return self._properties['description'] + Asynchronously retrieve a single page of AvailableAddOnInstance records from the API. + Request is executed immediately - @property - def pricing_type(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 AvailableAddOnInstance """ - :returns: How customers are charged for using this Add-on - :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 AvailableAddOnPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['pricing_type'] + Retrieve a single page with response metadata - @property - def configuration_schema(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: ApiResponse with AvailableAddOnPage, status code, and headers """ - :returns: The JSON object with the configuration that must be provided when installing a given Add-on - :rtype: dict + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AvailableAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['configuration_schema'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with AvailableAddOnPage, status code, and headers """ - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AvailableAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> AvailableAddOnPage: """ - return self._properties['url'] + Retrieve a specific page of AvailableAddOnInstance 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 AvailableAddOnInstance """ - :returns: The URLs of related resources - :rtype: unicode + response = self._version.domain.twilio.request("GET", target_url) + return AvailableAddOnPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AvailableAddOnPage: """ - return self._properties['links'] + Asynchronously retrieve a specific page of AvailableAddOnInstance 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 AvailableAddOnInstance """ - Fetch the AvailableAddOnInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return AvailableAddOnPage(self._version, response) - :returns: The fetched AvailableAddOnInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnInstance + def get(self, sid: str) -> AvailableAddOnContext: """ - return self._proxy.fetch() + Constructs a AvailableAddOnContext - @property - def extensions(self): + :param sid: The SID of the AvailableAddOn resource to fetch. """ - Access the extensions + return AvailableAddOnContext(self._version, sid=sid) - :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 __call__(self, sid: str) -> AvailableAddOnContext: """ - return self._proxy.extensions + Constructs a AvailableAddOnContext + + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + 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 80a3a6e87e..1d680e91c1 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,700 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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. """ +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") - def __init__(self, version, available_add_on_sid): - """ - Initialize the AvailableAddOnExtensionList + self._solution = { + "available_add_on_sid": available_add_on_sid, + "sid": sid or self.sid, + } - :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._context: Optional[AvailableAddOnExtensionContext] = None - :returns: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionList - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionList + @property + def _proxy(self) -> "AvailableAddOnExtensionContext": """ - super(AvailableAddOnExtensionList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'available_add_on_sid': available_add_on_sid, } - self._uri = '/AvailableAddOns/{available_add_on_sid}/Extensions'.format(**self._solution) + :returns: AvailableAddOnExtensionContext for this AvailableAddOnExtensionInstance + """ + if self._context is None: + self._context = AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def fetch(self) -> "AvailableAddOnExtensionInstance": """ - Streams AvailableAddOnExtensionInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Fetch the AvailableAddOnExtensionInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance] + :returns: The fetched AvailableAddOnExtensionInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "AvailableAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched AvailableAddOnExtensionInstance """ - Lists AvailableAddOnExtensionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return await self._proxy.fetch_async() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnExtensionInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance] + + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch_with_http_info() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of AvailableAddOnExtensionInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_with_http_info_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return AvailableAddOnExtensionPage(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 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 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 +class AvailableAddOnExtensionContext(InstanceContext): + + def __init__(self, version: Version, available_add_on_sid: str, sid: str): """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 ) - return AvailableAddOnExtensionPage(self._version, response, self._solution) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - def get(self, sid): + Returns: + tuple: (payload, status_code, headers) """ - Constructs a AvailableAddOnExtensionContext - :param sid: The SID of the AvailableAddOn Extension resource to fetch + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + 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 + def fetch(self) -> AvailableAddOnExtensionInstance: """ - return AvailableAddOnExtensionContext( + Fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + payload, _, _ = self._fetch() + 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a AvailableAddOnExtensionContext + Fetch the AvailableAddOnExtensionInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return AvailableAddOnExtensionContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -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. """ + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AvailableAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance - def __init__(self, version, response, solution): + + :returns: The fetched AvailableAddOnExtensionInstance + """ + payload, _, _ = await self._fetch_async() + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Initialize the AvailableAddOnExtensionPage + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance and return response metadata - :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 + :returns: ApiResponse with instance, status code, and headers """ - super(AvailableAddOnExtensionPage, self).__init__(version, response) + payload, status_code, headers = await self._fetch_async() + instance = AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - # Path Solution - self._solution = solution + def __repr__(self) -> str: + """ + Provide a friendly representation - def get_instance(self, payload): + :returns: Machine friendly representation """ - Build an instance of AvailableAddOnExtensionInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AvailableAddOnExtensionPage(Page): - :param dict payload: Payload response from the API + def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnExtensionInstance: + """ + Build an instance of AvailableAddOnExtensionInstance - :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) + self._solution = { + "available_add_on_sid": available_add_on_sid, + } + self._uri = "/AvailableAddOns/{available_add_on_sid}/Extensions".format( + **self._solution + ) - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AvailableAddOnExtensionInstance]: """ - Fetch the 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. - :returns: The fetched AvailableAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 AvailableAddOnExtensionInstance( - self._version, - payload, - available_add_on_sid=self._solution['available_add_on_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[AvailableAddOnExtensionInstance]: """ - Provide a friendly representation + 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. - :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"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AvailableAddOnExtensionInstance and returns headers from first page -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. """ - def __init__(self, version, payload, available_add_on_sid, sid=None): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Initialize the AvailableAddOnExtensionInstance + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(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 + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(AvailableAddOnExtensionInstance, self).__init__(version) + Asynchronously streams AvailableAddOnExtensionInstance and returns headers from first page - # 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'), - } - # Context - self._context = None - self._solution = { - 'available_add_on_sid': available_add_on_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: tuple of (generator, status_code, headers) where generator yields instances """ - 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_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :returns: AvailableAddOnExtensionContext for this AvailableAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionContext + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[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'], + 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, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnExtensionInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode + 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 self._properties['sid'] - @property - def available_add_on_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the AvailableAddOn resource to which this extension applies - :rtype: unicode + Lists AvailableAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['available_add_on_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def friendly_name(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Asynchronously lists AvailableAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['friendly_name'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def product_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, + ) -> AvailableAddOnExtensionPage: """ - :returns: The name of the Extension's Product - :rtype: unicode + 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['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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) + + async def 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: An application-defined string that uniquely identifies 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['unique_name'] + 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 AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailableAddOnExtensionPage, status code, and headers """ - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['url'] + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the 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: ApiResponse with AvailableAddOnExtensionPage, status code, and headers """ - Fetch the AvailableAddOnExtensionInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: The fetched AvailableAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> AvailableAddOnExtensionPage: """ - return self._proxy.fetch() + 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, solution=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, solution=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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 e2dc9a0e4f..c7352ed699 100644 --- a/twilio/rest/preview/marketplace/installed_add_on/__init__.py +++ b/twilio/rest/preview/marketplace/installed_add_on/__init__.py @@ -1,472 +1,1168 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +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") - def __init__(self, version): + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[InstalledAddOnContext] = None + + @property + def _proxy(self) -> "InstalledAddOnContext": """ - Initialize the InstalledAddOnList + 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: InstalledAddOnContext for this InstalledAddOnInstance + """ + if self._context is None: + self._context = InstalledAddOnContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnList - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnList + def delete(self) -> bool: """ - super(InstalledAddOnList, self).__init__(version) + Deletes the InstalledAddOnInstance - # Path Solution - self._solution = {} - self._uri = '/InstalledAddOns'.format(**self._solution) - def create(self, available_add_on_sid, accept_terms_of_service, - configuration=values.unset, unique_name=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the InstalledAddOnInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance - :returns: The created InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'AvailableAddOnSid': available_add_on_sid, - 'AcceptTermsOfService': accept_terms_of_service, - 'Configuration': serialize.object(configuration), - 'UniqueName': unique_name, - }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InstalledAddOnInstance with HTTP info - return InstalledAddOnInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "InstalledAddOnInstance": + """ + Fetch the InstalledAddOnInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "InstalledAddOnInstance": + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance - :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 await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of InstalledAddOnInstance records from the API. - Request is executed immediately + Fetch the InstalledAddOnInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Asynchronous coroutine to fetch the InstalledAddOnInstance with HTTP info - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return InstalledAddOnPage(self._version, response, self._solution) + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() - 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) + 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. - def get(self, sid): + :returns: The updated InstalledAddOnInstance """ - Constructs a InstalledAddOnContext + return await self._proxy.update_async( + configuration=configuration, + unique_name=unique_name, + ) - :param sid: The SID of the InstalledAddOn resource to fetch + def update_with_http_info( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the InstalledAddOnInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers """ - return InstalledAddOnContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + configuration=configuration, + unique_name=unique_name, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Constructs a InstalledAddOnContext + Asynchronous coroutine to update the InstalledAddOnInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return InstalledAddOnContext(self._version, sid=sid, ) + return await self._proxy.update_with_http_info_async( + configuration=configuration, + unique_name=unique_name, + ) - def __repr__(self): + @property + def extensions(self) -> InstalledAddOnExtensionList: + """ + Access the extensions + """ + return self._proxy.extensions + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class InstalledAddOnPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class InstalledAddOnContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the InstalledAddOnPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the InstalledAddOnContext - :returns: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnPage - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnPage + :param version: Version that contains the resource + :param sid: The SID of the InstalledAddOn resource to update. """ - super(InstalledAddOnPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/InstalledAddOns/{sid}".format(**self._solution) - def get_instance(self, payload): - """ - Build an instance of InstalledAddOnInstance + self._extensions: Optional[InstalledAddOnExtensionList] = None - :param dict payload: Payload response from the API + def _delete(self) -> tuple: + """ + Internal helper for delete operation - :returns: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - return InstalledAddOnInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - Provide a friendly representation + Deletes the InstalledAddOnInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + success, _, _ = self._delete() + return success + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InstalledAddOnInstance and return response metadata -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. """ - def __init__(self, version, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the InstalledAddOnContext + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :param Version version: Version that contains the resource - :param sid: The SID of the InstalledAddOn resource to fetch + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation - :returns: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnContext - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnContext + Returns: + tuple: (success_boolean, status_code, headers) """ - 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 + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - def delete(self): + async def delete_async(self) -> bool: """ - Deletes the InstalledAddOnInstance + Asynchronous coroutine that deletes the InstalledAddOnInstance + :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance and return response metadata + - def fetch(self): + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InstalledAddOnInstance: """ 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, ) + payload, _, _ = self._fetch() + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - return InstalledAddOnInstance(self._version, payload, sid=self._solution['sid'], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" - def update(self, configuration=values.unset, unique_name=values.unset): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> InstalledAddOnInstance: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + payload, _, _ = await self._fetch_async() + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + configuration=configuration, unique_name=unique_name + ) + return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the InstalledAddOnInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + configuration=configuration, unique_name=unique_name + ) + instance = InstalledAddOnInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance """ - data = values.of({'Configuration': serialize.object(configuration), 'UniqueName': unique_name, }) + payload, _, _ = await self._update_async( + configuration=configuration, unique_name=unique_name + ) + return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + async def update_with_http_info_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnInstance and return response metadata + + :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. - return InstalledAddOnInstance(self._version, payload, sid=self._solution['sid'], ) + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + configuration=configuration, unique_name=unique_name + ) + instance = InstalledAddOnInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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'), - } +class InstalledAddOnPage(Page): - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnInstance: + """ + Build an instance of InstalledAddOnInstance - @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 - :returns: InstalledAddOnContext for this InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnContext + return InstalledAddOnInstance(self._version, payload) + + def __repr__(self) -> str: """ - if self._context is None: - self._context = InstalledAddOnContext(self._version, 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 InstalledAddOnList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['sid'] + Initialize the InstalledAddOnList + + :param version: Version that contains the resource - @property - def account_sid(self): """ - :returns: The SID of the Account that created 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, + ) -> tuple: """ - return self._properties['account_sid'] + Internal helper for create operation - @property - def friendly_name(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The string that you assigned to describe the resource - :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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + payload, _, _ = self._create( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + return InstalledAddOnInstance(self._version, payload) + + def create_with_http_info( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the InstalledAddOnInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + instance = InstalledAddOnInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + payload, _, _ = await self._create_async( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + return InstalledAddOnInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the InstalledAddOnInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + instance = InstalledAddOnInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_created'] + Streams InstalledAddOnInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :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_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_updated'] + Asynchronously streams InstalledAddOnInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The absolute URL of the resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnInstance]: """ - return self._properties['url'] + 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 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 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[InstalledAddOnInstance]: """ - return self._properties['links'] + 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. - 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 """ - Deletes the InstalledAddOnInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.delete() + Lists InstalledAddOnInstance and returns headers from first page - 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: ApiResponse with list of instances, status code, and headers """ - Fetch the InstalledAddOnInstance + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: The fetched InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.fetch() + Asynchronously lists InstalledAddOnInstance and returns headers from first page - def update(self, configuration=values.unset, unique_name=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: ApiResponse with list of instances, status code, and headers """ - Update the InstalledAddOnInstance + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - :param dict configuration: The JSON object representing the configuration - :param unicode unique_name: An application-defined string that uniquely identifies the resource + 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 - :returns: The updated InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance + :param page_token: PageToken provided by the API + :param page_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 """ - return self._proxy.update(configuration=configuration, unique_name=unique_name, ) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def extensions(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 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: """ - Access the extensions + 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: 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 + :returns: Page of InstalledAddOnInstance """ - return self._proxy.extensions + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InstalledAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InstalledAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 58ec6d7263..0c7f88938d 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,862 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class InstalledAddOnExtensionList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class InstalledAddOnExtensionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the InstalledAddOn Extension resource. + :ivar installed_add_on_sid: The SID of the InstalledAddOn resource to which this extension applies. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar product_name: The name of the Product this Extension is used within. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :ivar enabled: Whether the Extension will be invoked. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + installed_add_on_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.installed_add_on_sid: Optional[str] = payload.get("installed_add_on_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product_name: Optional[str] = payload.get("product_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.enabled: Optional[bool] = payload.get("enabled") + self.url: Optional[str] = payload.get("url") - def __init__(self, version, installed_add_on_sid): - """ - Initialize the InstalledAddOnExtensionList + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + "sid": sid or self.sid, + } - :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._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) + 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 = {'installed_add_on_sid': installed_add_on_sid, } - self._uri = '/InstalledAddOns/{installed_add_on_sid}/Extensions'.format(**self._solution) + :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 stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the InstalledAddOnExtensionInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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 """ - 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) -> "InstalledAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnExtensionInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance] + + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch_with_http_info() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of InstalledAddOnExtensionInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of InstalledAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionPage + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_with_http_info_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def update(self, enabled: bool) -> "InstalledAddOnExtensionInstance": + """ + 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 self._proxy.update( + enabled=enabled, + ) + + async def update_async(self, enabled: bool) -> "InstalledAddOnExtensionInstance": + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance - :param str target_url: API-generated URL for the requested results page + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + enabled=enabled, ) - return InstalledAddOnExtensionPage(self._version, response, self._solution) - - def get(self, sid): + def update_with_http_info(self, enabled: bool) -> ApiResponse: """ - Constructs a InstalledAddOnExtensionContext + Update the InstalledAddOnExtensionInstance with HTTP info - :param sid: The SID of the InstalledAddOn Extension resource to fetch + :param enabled: Whether the Extension should be invoked. - :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: ApiResponse with instance, status code, and headers """ - return InstalledAddOnExtensionContext( - self._version, - installed_add_on_sid=self._solution['installed_add_on_sid'], - sid=sid, + return self._proxy.update_with_http_info( + enabled=enabled, ) - def __call__(self, sid): + async def update_with_http_info_async(self, enabled: bool) -> ApiResponse: """ - Constructs a InstalledAddOnExtensionContext + Asynchronous coroutine to update the InstalledAddOnExtensionInstance with HTTP info - :param sid: The SID of the InstalledAddOn Extension resource to fetch + :param enabled: Whether the Extension should be invoked. - :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: ApiResponse with instance, status code, and headers """ - return InstalledAddOnExtensionContext( - self._version, - installed_add_on_sid=self._solution['installed_add_on_sid'], - sid=sid, + return await self._proxy.update_with_http_info_async( + enabled=enabled, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) -class 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. """ +class InstalledAddOnExtensionContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, installed_add_on_sid: str, sid: str): """ - Initialize the InstalledAddOnExtensionPage - - :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 + Initialize the InstalledAddOnExtensionContext - :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 + :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(InstalledAddOnExtensionPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - Build an instance of InstalledAddOnExtensionInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :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 + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InstalledAddOnExtensionInstance: """ + Fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + payload, _, _ = self._fetch() 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 fetch_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Fetch the InstalledAddOnExtensionInstance and return response metadata - :returns: Machine friendly representation - :rtype: str - """ - return '' + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) -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. """ + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - def __init__(self, version, installed_add_on_sid, sid): + Returns: + tuple: (payload, status_code, headers) """ - Initialize the InstalledAddOnExtensionContext - :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 + headers = values.of({}) - :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 - """ - super(InstalledAddOnExtensionContext, self).__init__(version) + headers["Accept"] = "application/json" - # 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) + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + async def fetch_async(self) -> InstalledAddOnExtensionInstance: """ - Fetch the InstalledAddOnExtensionInstance + Asynchronous coroutine to 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, ) - + payload, _, _ = await self._fetch_async() 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"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, enabled: bool) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers ) - def update(self, enabled): + def update(self, enabled: bool) -> InstalledAddOnExtensionInstance: """ Update the InstalledAddOnExtensionInstance - :param bool enabled: Whether the Extension should be invoked + :param enabled: Whether the Extension should be invoked. :returns: The updated InstalledAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance """ - data = values.of({'Enabled': enabled, }) + payload, _, _ = self._update(enabled=enabled) + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info(self, enabled: bool) -> ApiResponse: + """ + Update the InstalledAddOnExtensionInstance and return response metadata - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :param enabled: Whether the Extension should be invoked. + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(enabled=enabled) + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, enabled: bool) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(enabled=enabled) 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 __repr__(self): + async def update_with_http_info_async(self, enabled: bool) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance and return response metadata + + :param enabled: Whether the Extension should be invoked. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(enabled=enabled) + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide 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 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 InstalledAddOnExtensionPage(Page): - def __init__(self, version, payload, installed_add_on_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnExtensionInstance: """ - Initialize the InstalledAddOnExtensionInstance + Build an instance of InstalledAddOnExtensionInstance - :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 + :param payload: Payload response from the API """ - super(InstalledAddOnExtensionInstance, self).__init__(version) - # 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'), - } + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) - # Context - self._context = None + 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, - '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 + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = InstalledAddOnExtensionContext( - self._version, - installed_add_on_sid=self._solution['installed_add_on_sid'], - sid=self._solution['sid'], + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InstalledAddOnExtensionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InstalledAddOnExtensionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnExtensionInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode + 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 self._properties['sid'] - @property - def installed_add_on_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the InstalledAddOn resource to which this extension applies - :rtype: unicode + Lists InstalledAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['installed_add_on_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def friendly_name(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Asynchronously lists InstalledAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['friendly_name'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def product_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, + ) -> InstalledAddOnExtensionPage: """ - :returns: The name of the Extension's Product - :rtype: unicode + 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 """ - 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) + + async def 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: """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + 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 """ - return self._properties['unique_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def enabled(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 InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: Whether the Extension will be invoked - :rtype: bool + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnExtensionPage, status code, and headers """ - return self._properties['enabled'] + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnExtensionPage, status code, and headers """ - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> InstalledAddOnExtensionPage: """ - return self._properties['url'] + 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 = self._version.domain.twilio.request("GET", target_url) + return InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) - :returns: The fetched InstalledAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance + async def get_page_async(self, target_url: str) -> InstalledAddOnExtensionPage: """ - return self._proxy.fetch() + 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 update(self, enabled): + :returns: Page of InstalledAddOnExtensionInstance """ - Update the InstalledAddOnExtensionInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) - :param bool enabled: Whether the Extension should be invoked + def get(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 __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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 6243f0dc3e..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists ServiceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.ServiceInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of ServiceInstance - :rtype: twilio.rest.preview.sync.service.ServicePage - """ - 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 ad7f64de66..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists DocumentInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.document.DocumentInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of DocumentInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of DocumentInstance - :rtype: twilio.rest.preview.sync.service.document.DocumentPage - """ - 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 b10ea2f9ce..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists DocumentPermissionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of DocumentPermissionInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of DocumentPermissionInstance - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionPage - """ - 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 44d40c95a4..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists SyncListInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_list.SyncListInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of SyncListInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncListInstance - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListPage - """ - 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 a54e131f77..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'], limits['page_limit']) - - def list(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): - """ - Lists SyncListItemInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param SyncListItemInstance.QueryResultOrder order: The order - :param unicode from_: The from - :param SyncListItemInstance.QueryFromBoundType bounds: The bounds - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance] - """ - return list(self.stream(order=order, from_=from_, bounds=bounds, limit=limit, page_size=page_size, )) - - def page(self, order=values.unset, from_=values.unset, bounds=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of SyncListItemInstance records from the API. - Request is executed immediately - - :param SyncListItemInstance.QueryResultOrder order: The order - :param unicode from_: The from - :param SyncListItemInstance.QueryFromBoundType bounds: The bounds - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncListItemInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemPage - """ - 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 508a8e79e5..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists SyncListPermissionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of SyncListPermissionInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncListPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionPage - """ - 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 7c7d5952f8..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists SyncMapInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_map.SyncMapInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of SyncMapInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncMapInstance - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapPage - """ - 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 229d631c88..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'], limits['page_limit']) - - def list(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): - """ - Lists SyncMapItemInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param SyncMapItemInstance.QueryResultOrder order: The order - :param unicode from_: The from - :param SyncMapItemInstance.QueryFromBoundType bounds: The bounds - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance] - """ - return list(self.stream(order=order, from_=from_, bounds=bounds, limit=limit, page_size=page_size, )) - - def page(self, order=values.unset, from_=values.unset, bounds=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of SyncMapItemInstance records from the API. - Request is executed immediately - - :param SyncMapItemInstance.QueryResultOrder order: The order - :param unicode from_: The from - :param SyncMapItemInstance.QueryFromBoundType bounds: The bounds - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncMapItemInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemPage - """ - 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 84172aa018..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists SyncMapPermissionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of SyncMapPermissionInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncMapPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionPage - """ - 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 d72cee1403..0000000000 --- a/twilio/rest/preview/trusted_comms/__init__.py +++ /dev/null @@ -1,86 +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.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._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 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/business/__init__.py b/twilio/rest/preview/trusted_comms/business/__init__.py deleted file mode 100644 index cb179e99f4..0000000000 --- a/twilio/rest/preview/trusted_comms/business/__init__.py +++ /dev/null @@ -1,265 +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.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._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 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 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/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 ea60053ea4..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists AssistantInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.AssistantInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of AssistantInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of AssistantInstance - :rtype: twilio.rest.preview.understand.assistant.AssistantPage - """ - 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 b5588f8a0c..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists FieldTypeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of FieldTypeInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of FieldTypeInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypePage - """ - 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 ffbc253f18..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'], limits['page_limit']) - - def list(self, language=values.unset, limit=None, page_size=None): - """ - Lists FieldValueInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode language: 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 199a545d72..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists ModelBuildInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.model_build.ModelBuildInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of ModelBuildInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of ModelBuildInstance - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildPage - """ - 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 494802380c..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'], limits['page_limit']) - - def list(self, language=values.unset, model_build=values.unset, - status=values.unset, limit=None, page_size=None): - """ - Lists QueryInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode language: 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 7b4cc8c08c..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'], limits['page_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 9bd6142c10..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists FieldInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.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 19ff094fb8..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'], limits['page_limit']) - - def list(self, language=values.unset, limit=None, page_size=None): - """ - Lists SampleInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode language: 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 8290de54df..1ca73b5b3b 100644 --- a/twilio/rest/preview/wireless/command.py +++ b/twilio/rest/preview/wireless/command.py @@ -1,448 +1,1030 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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. """ +class CommandInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar device_sid: + :ivar sim_sid: + :ivar command: + :ivar command_mode: + :ivar status: + :ivar direction: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.device_sid: Optional[str] = payload.get("device_sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.command: Optional[str] = payload.get("command") + self.command_mode: Optional[str] = payload.get("command_mode") + self.status: Optional[str] = payload.get("status") + self.direction: Optional[str] = payload.get("direction") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[CommandContext] = None - def __init__(self, version): + @property + def _proxy(self) -> "CommandContext": """ - Initialize the CommandList + 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: CommandContext for this CommandInstance + """ + if self._context is None: + self._context = CommandContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.preview.wireless.command.CommandList - :rtype: twilio.rest.preview.wireless.command.CommandList + def fetch(self) -> "CommandInstance": """ - super(CommandList, self).__init__(version) + Fetch the CommandInstance - # Path Solution - self._solution = {} - self._uri = '/Commands'.format(**self._solution) - def stream(self, device=values.unset, sim=values.unset, status=values.unset, - direction=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() + + async def fetch_async(self) -> "CommandInstance": + """ + 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. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.fetch_async() - page = self.page( - device=device, - sim=sim, - status=status, - direction=direction, - page_size=limits['page_size'], - ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CommandInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, device=values.unset, sim=values.unset, status=values.unset, - direction=values.unset, limit=None, page_size=None): + :returns: ApiResponse with instance, status code, and headers """ - Lists CommandInstance 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_with_http_info() - :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) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CommandInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.wireless.command.CommandInstance] + + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream( - device=device, - sim=sim, - status=status, - direction=direction, - limit=limit, - page_size=page_size, - )) + return await self._proxy.fetch_with_http_info_async() - def page(self, device=values.unset, sim=values.unset, status=values.unset, - direction=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of CommandInstance records from the API. - Request is executed immediately + Provide a friendly representation - :param unicode device: The device - :param unicode sim: The sim - :param unicode status: The status - :param unicode direction: The direction - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Page of CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandPage + +class CommandContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - data = values.of({ - 'Device': device, - 'Sim': sim, - 'Status': status, - 'Direction': direction, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Initialize the CommandContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) - return CommandPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Commands/{sid}".format(**self._solution) - def get_page(self, target_url): + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - 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 + headers = values.of({}) - :returns: Page of CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandPage + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CommandInstance: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + payload, _, _ = self._fetch() + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CommandPage(self._version, response, self._solution) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CommandInstance and return response metadata - def create(self, command, device=values.unset, sim=values.unset, - callback_method=values.unset, callback_url=values.unset, - command_mode=values.unset, include_sid=values.unset): + + :returns: ApiResponse with instance, status code, and headers """ - Create the CommandInstance + payload, status_code, headers = self._fetch() + instance = CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :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 + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: The created CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandInstance + Returns: + tuple: (payload, status_code, headers) """ - 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({}) + + headers["Accept"] = "application/json" - return CommandInstance(self._version, payload, ) + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def get(self, sid): + async def fetch_async(self) -> CommandInstance: """ - Constructs a CommandContext + Asynchronous coroutine to fetch the CommandInstance - :param sid: The sid - :returns: twilio.rest.preview.wireless.command.CommandContext - :rtype: twilio.rest.preview.wireless.command.CommandContext + :returns: The fetched CommandInstance """ - return CommandContext(self._version, sid=sid, ) + payload, _, _ = await self._fetch_async() + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __call__(self, sid): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Constructs a CommandContext + Asynchronous coroutine to fetch the CommandInstance and return response metadata - :param sid: The sid - :returns: twilio.rest.preview.wireless.command.CommandContext - :rtype: twilio.rest.preview.wireless.command.CommandContext + :returns: ApiResponse with instance, status code, and headers """ - return CommandContext(self._version, sid=sid, ) + payload, status_code, headers = await self._fetch_async() + instance = CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class CommandPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - def __init__(self, version, response, solution): + def get_instance(self, payload: Dict[str, Any]) -> CommandInstance: """ - Initialize the CommandPage + Build an instance of CommandInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API + :param payload: Payload response from the API + """ + + return CommandInstance(self._version, payload) - :returns: twilio.rest.preview.wireless.command.CommandPage - :rtype: twilio.rest.preview.wireless.command.CommandPage + def __repr__(self) -> str: """ - super(CommandPage, self).__init__(version, response) + Provide a friendly representation - # Path Solution - self._solution = solution + :returns: Machine friendly representation + """ + return "" + + +class CommandList(ListResource): - def get_instance(self, payload): + def __init__(self, version: Version): """ - Build an instance of CommandInstance + Initialize the CommandList - :param dict payload: Payload response from the API + :param version: Version that contains the resource - :returns: twilio.rest.preview.wireless.command.CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandInstance """ - return CommandInstance(self._version, payload, ) + super().__init__(version) + + self._uri = "/Commands" + + def _create( + self, + command: str, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union[str, object] = values.unset, + include_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation - def __repr__(self): + Returns: + tuple: (payload, status_code, headers) """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + data = values.of( + { + "Command": command, + "Device": device, + "Sim": sim, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "CommandMode": command_mode, + "IncludeSid": include_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return '' + Create the CommandInstance + :param command: + :param device: + :param sim: + :param callback_method: + :param callback_url: + :param command_mode: + :param include_sid: -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. """ + :returns: The created CommandInstance + """ + payload, _, _ = self._create( + command=command, + device=device, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + ) + return CommandInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the CommandInstance and return response metadata - def __init__(self, version, sid): + :param command: + :param device: + :param sim: + :param callback_method: + :param callback_url: + :param command_mode: + :param include_sid: + + :returns: ApiResponse with instance, status code, and headers """ - Initialize the CommandContext + payload, status_code, headers = self._create( + command=command, + device=device, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + ) + instance = CommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation - :param Version version: Version that contains the resource - :param sid: The sid + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Command": command, + "Device": device, + "Sim": sim, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "CommandMode": command_mode, + "IncludeSid": include_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - :returns: twilio.rest.preview.wireless.command.CommandContext - :rtype: twilio.rest.preview.wireless.command.CommandContext + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - super(CommandContext, self).__init__(version) + Asynchronously create the CommandInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Commands/{sid}'.format(**self._solution) + :param command: + :param device: + :param sim: + :param callback_method: + :param callback_url: + :param command_mode: + :param include_sid: - def fetch(self): + :returns: The created CommandInstance """ - Fetch the CommandInstance + payload, _, _ = await self._create_async( + command=command, + device=device, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + ) + return CommandInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the CommandInstance and return response metadata - :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + command=command, + device=device, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + ) + instance = CommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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]: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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. - return CommandInstance(self._version, payload, sid=self._solution['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) - 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( + device=device, + sim=sim, + status=status, + direction=direction, + page_size=limits["page_size"], + ) - :returns: Machine friendly representation - :rtype: str + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CommandInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Asynchronously streams CommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + :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) -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'), - } + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + device=device, + sim=sim, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams CommandInstance and returns headers from first page - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): + :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: tuple of (generator, status_code, headers) where generator yields instances """ - 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_response = self.page_with_http_info( + device=device, + sim=sim, + status=status, + direction=direction, + page_size=limits["page_size"], + ) - :returns: CommandContext for this CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandContext + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - if self._context is None: - self._context = CommandContext(self._version, sid=self._solution['sid'], ) - return self._context + Asynchronously streams CommandInstance and returns headers from first page - @property - def sid(self): + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The sid - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + device=device, + sim=sim, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - return self._properties['sid'] + Lists CommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def account_sid(self): + :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 """ - :returns: The account_sid - :rtype: unicode + + 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]: """ - return self._properties['account_sid'] + Asynchronously lists CommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def device_sid(self): + :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 """ - :returns: The device_sid - :rtype: unicode + + 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 list_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['device_sid'] + Lists CommandInstance and returns headers from first page - @property - def sim_sid(self): + + :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: ApiResponse with list of instances, status code, and headers """ - :returns: The sim_sid - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + device=device, + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['sim_sid'] + Asynchronously lists CommandInstance and returns headers from first page - @property - def command(self): + + :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: ApiResponse with list of instances, status code, and headers """ - :returns: The command - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + device=device, + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['command'] + Retrieve a single page of CommandInstance records from the API. + Request is executed immediately - @property - def command_mode(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 command_mode - :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: """ - return self._properties['command_mode'] + Asynchronously retrieve a single page of CommandInstance records from the API. + Request is executed immediately - @property - def status(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 status - :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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CommandPage(self._version, response) + + def page_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['status'] + Retrieve a single page with response metadata - @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: ApiResponse with CommandPage, status code, and headers """ - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['direction'] + Asynchronously retrieve a single page with response metadata - @property - def date_created(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: ApiResponse with CommandPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 3918601905..46a4445e4d 100644 --- a/twilio/rest/preview/wireless/rate_plan.py +++ b/twilio/rest/preview/wireless/rate_plan.py @@ -1,495 +1,1252 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[RatePlanContext] = None - def __init__(self, version): + @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 + """ + return self._proxy.delete() + + async def delete_async(self) -> 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. + Asynchronous coroutine that deletes the RatePlanInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.wireless.rate_plan.RatePlanInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RatePlanInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists RatePlanInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RatePlanInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.wireless.rate_plan.RatePlanInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "RatePlanInstance": """ - Retrieve a single page of RatePlanInstance records from the API. - Request is executed immediately + Fetch the RatePlanInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanPage + :returns: The fetched RatePlanInstance """ - 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) -> "RatePlanInstance": + """ + Asynchronous coroutine to fetch the RatePlanInstance - return RatePlanPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched RatePlanInstance """ - Retrieve a specific page of RatePlanInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RatePlanInstance with HTTP info - :returns: Page of RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() - return RatePlanPage(self._version, response, self._solution) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RatePlanInstance with HTTP info - 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): + + :returns: ApiResponse with instance, status code, and headers """ - Create the RatePlanInstance + return await self._proxy.fetch_with_http_info_async() - :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 + def update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": + """ + Update the RatePlanInstance - :returns: The created RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanInstance + :param unique_name: + :param friendly_name: + + :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), - }) + return self._proxy.update( + unique_name=unique_name, + friendly_name=friendly_name, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": + """ + Asynchronous coroutine to update the RatePlanInstance - return RatePlanInstance(self._version, payload, ) + :param unique_name: + :param friendly_name: - def get(self, sid): + :returns: The updated RatePlanInstance """ - Constructs a RatePlanContext + return await self._proxy.update_async( + unique_name=unique_name, + friendly_name=friendly_name, + ) - :param sid: The sid + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RatePlanInstance with HTTP info - :returns: twilio.rest.preview.wireless.rate_plan.RatePlanContext - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanContext + :param unique_name: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers """ - return RatePlanContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + unique_name=unique_name, + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Constructs a RatePlanContext + Asynchronous coroutine to update the RatePlanInstance with HTTP info - :param sid: The sid + :param unique_name: + :param friendly_name: - :returns: twilio.rest.preview.wireless.rate_plan.RatePlanContext - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanContext + :returns: ApiResponse with instance, status code, and headers """ - return RatePlanContext(self._version, sid=sid, ) + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + friendly_name=friendly_name, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class RatePlanPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class RatePlanContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the RatePlanPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the RatePlanContext - :returns: twilio.rest.preview.wireless.rate_plan.RatePlanPage - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanPage + :param version: Version that contains the resource + :param sid: """ - super(RatePlanPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/RatePlans/{sid}".format(**self._solution) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of RatePlanInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the RatePlanInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.preview.wireless.rate_plan.RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanInstance + :returns: True if delete succeeds, False otherwise """ - return RatePlanInstance(self._version, payload, ) + success, _, _ = self._delete() + return success - def __repr__(self): + def delete_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Deletes the RatePlanInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with success boolean, status code, and headers """ - return '' + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation -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. """ + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + async def delete_async(self) -> bool: """ - Initialize the RatePlanContext + Asynchronous coroutine that deletes 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: True if delete succeeds, False otherwise """ - super(RatePlanContext, self).__init__(version) + success, _, _ = await self._delete_async() + return success - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RatePlans/{sid}'.format(**self._solution) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RatePlanInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RatePlanInstance: """ Fetch the RatePlanInstance + :returns: The fetched RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RatePlanInstance and return response metadata - return RatePlanInstance(self._version, payload, sid=self._solution['sid'], ) - def update(self, unique_name=values.unset, friendly_name=values.unset): + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RatePlanInstance: + """ + Asynchronous coroutine to fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + payload, _, _ = await self._fetch_async() + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RatePlanInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._update( + unique_name=unique_name, friendly_name=friendly_name + ) + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RatePlanInstance and return response metadata - return RatePlanInstance(self._version, payload, sid=self._solution['sid'], ) + :param unique_name: + :param friendly_name: - def delete(self): + :returns: ApiResponse with instance, status code, and headers """ - Deletes the RatePlanInstance + payload, status_code, headers = self._update( + unique_name=unique_name, friendly_name=friendly_name + ) + instance = RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def _update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Asynchronous coroutine to update the RatePlanInstance + + :param unique_name: + :param friendly_name: - def __repr__(self): + :returns: The updated RatePlanInstance + """ + payload, _, _ = await self._update_async( + unique_name=unique_name, friendly_name=friendly_name + ) + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RatePlanInstance and return response metadata + + :param unique_name: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + unique_name=unique_name, friendly_name=friendly_name + ) + instance = RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide 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'), - } +class RatePlanPage(Page): - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + def get_instance(self, payload: Dict[str, Any]) -> RatePlanInstance: + """ + Build an instance of RatePlanInstance - @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 - :returns: RatePlanContext for this RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanContext + return RatePlanInstance(self._version, payload) + + def __repr__(self) -> str: """ - if self._context is None: - self._context = RatePlanContext(self._version, sid=self._solution['sid'], ) - return self._context + Provide a friendly representation - @property - def sid(self): + :returns: Machine friendly representation """ - :returns: The sid - :rtype: unicode + return "" + + +class RatePlanList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['sid'] + Initialize the RatePlanList - @property - def unique_name(self): + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RatePlans" + + def _create( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + commands_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - :returns: The unique_name - :rtype: unicode + 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['unique_name'] + payload, _, _ = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + commands_enabled=commands_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + ) + return RatePlanInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the RatePlanInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + commands_enabled=commands_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + ) + instance = RatePlanInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "DataMetering": data_metering, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "CommandsEnabled": serialize.boolean_to_string(commands_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), + "InternationalRoaming": serialize.map( + international_roaming, lambda e: e + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def account_sid(self): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - :returns: The account_sid - :rtype: unicode + payload, _, _ = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + commands_enabled=commands_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + ) + return RatePlanInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the RatePlanInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + commands_enabled=commands_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + ) + instance = RatePlanInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RatePlanInstance]: """ - return self._properties['account_sid'] + 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. - @property - def friendly_name(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The friendly_name - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RatePlanInstance]: """ - return self._properties['friendly_name'] + 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. - @property - def data_enabled(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The data_enabled - :rtype: bool + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['data_enabled'] + Streams RatePlanInstance and returns headers from first page - @property - def data_metering(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The data_metering - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['data_metering'] + Asynchronously streams RatePlanInstance and returns headers from first page - @property - def data_limit(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The data_limit - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RatePlanInstance]: """ - return self._properties['data_limit'] + Lists RatePlanInstance 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_enabled(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 messaging_enabled - :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[RatePlanInstance]: """ - return self._properties['messaging_enabled'] + 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. - @property - def voice_enabled(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 voice_enabled - :rtype: bool + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['voice_enabled'] + Lists RatePlanInstance and returns headers from first page - @property - def national_roaming_enabled(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: ApiResponse with list of instances, status code, and headers """ - :returns: The national_roaming_enabled - :rtype: bool + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['national_roaming_enabled'] + Asynchronously lists RatePlanInstance and returns headers from first page - @property - def international_roaming(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: ApiResponse with list of instances, status code, and headers """ - :returns: The international_roaming - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['international_roaming'] + Retrieve a single page of RatePlanInstance 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 RatePlanInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RatePlanPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RatePlanPage: """ - :returns: The date_created - :rtype: datetime + Asynchronously retrieve a single page of RatePlanInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RatePlanInstance """ - 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 RatePlanPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The date_updated - :rtype: datetime + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RatePlanPage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RatePlanPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The url - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RatePlanPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RatePlanPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - def fetch(self): + def get_page(self, target_url: str) -> RatePlanPage: """ - Fetch the RatePlanInstance + Retrieve a specific page of RatePlanInstance records from the API. + Request is executed immediately - :returns: The fetched RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of RatePlanInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return RatePlanPage(self._version, response) - def update(self, unique_name=values.unset, friendly_name=values.unset): + async def get_page_async(self, target_url: str) -> RatePlanPage: """ - Update the RatePlanInstance + Asynchronously retrieve a specific page of RatePlanInstance records from the API. + Request is executed immediately - :param unicode unique_name: The unique_name - :param unicode friendly_name: The friendly_name + :param target_url: API-generated URL for the requested results page - :returns: The updated RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanInstance + :returns: Page of RatePlanInstance """ - return self._proxy.update(unique_name=unique_name, friendly_name=friendly_name, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return RatePlanPage(self._version, response) - def delete(self): + def get(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 __call__(self, sid: str) -> RatePlanContext: + """ + Constructs a RatePlanContext + + :param sid: + """ + 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 7ef91524c2..ac6b78788d 100644 --- a/twilio/rest/preview/wireless/sim/__init__.py +++ b/twilio/rest/preview/wireless/sim/__init__.py @@ -1,657 +1,1496 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +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") - def __init__(self, version): - """ - Initialize the SimList + self._solution = { + "sid": sid or self.sid, + } - :param Version version: Version that contains the resource + self._context: Optional[SimContext] = None - :returns: twilio.rest.preview.wireless.sim.SimList - :rtype: twilio.rest.preview.wireless.sim.SimList + @property + def _proxy(self) -> "SimContext": """ - super(SimList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Sims'.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, status=values.unset, iccid=values.unset, - rate_plan=values.unset, e_id=values.unset, - sim_registration_code=values.unset, limit=None, page_size=None): + :returns: SimContext for this 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 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) + 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.preview.wireless.sim.SimInstance] + def fetch(self) -> "SimInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch 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'], limits['page_limit']) + :returns: The fetched SimInstance + """ + return self._proxy.fetch() - 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 fetch_async(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. + 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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 await self._proxy.fetch_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_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of SimInstance records from the API. - Request is executed immediately + Fetch the SimInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - 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_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SimInstance with HTTP info - return SimPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of SimInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page - - :returns: Page of SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimPage + 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": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Update the SimInstance - return SimPage(self._version, response, self._solution) + :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 get(self, sid): + :returns: The updated SimInstance """ - Constructs a SimContext + return self._proxy.update( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + ) - :param sid: The sid + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> "SimInstance": + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: - :returns: 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): - """ - Constructs a SimContext + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the SimInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + ) - :param sid: The sid + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SimInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + ) - :returns: twilio.rest.preview.wireless.sim.SimContext - :rtype: twilio.rest.preview.wireless.sim.SimContext + @property + def usage(self) -> UsageList: + """ + Access the usage """ - return SimContext(self._version, sid=sid, ) + return self._proxy.usage - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SimPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class SimContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the SimPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the SimContext - :returns: twilio.rest.preview.wireless.sim.SimPage - :rtype: twilio.rest.preview.wireless.sim.SimPage + :param version: Version that contains the resource + :param sid: """ - super(SimPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Sims/{sid}".format(**self._solution) - def get_instance(self, payload): - """ - Build an instance of SimInstance + self._usage: Optional[UsageList] = None - :param dict payload: Payload response from the API + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.preview.wireless.sim.SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimInstance + Returns: + tuple: (payload, status_code, headers) """ - return SimInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SimInstance: """ - Provide a friendly representation + Fetch the SimInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched SimInstance """ - return '' + payload, _, _ = self._fetch() + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SimInstance and return response metadata -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): + :returns: ApiResponse with instance, status code, and headers """ - Initialize the SimContext + payload, status_code, headers = self._fetch() + instance = SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param Version version: Version that contains the resource - :param sid: The sid + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: twilio.rest.preview.wireless.sim.SimContext - :rtype: twilio.rest.preview.wireless.sim.SimContext + Returns: + tuple: (payload, status_code, headers) """ - super(SimContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Sims/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._usage = None + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + async def fetch_async(self) -> SimInstance: """ - Fetch the SimInstance + Asynchronous coroutine to fetch the SimInstance + :returns: The fetched SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = await self._fetch_async() + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SimInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" - return SimInstance(self._version, payload, sid=self._solution['sid'], ) + 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): + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> SimInstance: """ Update the SimInstance - :param unicode unique_name: The unique_name - :param unicode callback_method: The callback_method - :param unicode callback_url: The callback_url - :param unicode friendly_name: The friendly_name - :param unicode rate_plan: The rate_plan - :param unicode status: The status - :param unicode commands_callback_method: The commands_callback_method - :param unicode commands_callback_url: The commands_callback_url - :param unicode sms_fallback_method: The sms_fallback_method - :param unicode sms_fallback_url: The sms_fallback_url - :param unicode sms_method: The sms_method - :param unicode sms_url: The sms_url - :param unicode voice_fallback_method: The voice_fallback_method - :param unicode voice_fallback_url: The voice_fallback_url - :param unicode voice_method: The voice_method - :param unicode voice_url: The voice_url + :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 + """ + payload, _, _ = self._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 SimInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the SimInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = SimInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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'], ) + """ + payload, _, _ = await self._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, + ) + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SimInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = SimInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + return SimInstance(self._version, payload) - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['unique_name'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def rate_plan_sid(self): - """ - :returns: The rate_plan_sid - :rtype: unicode - """ - return self._properties['rate_plan_sid'] - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] +class SimList(ListResource): - @property - def iccid(self): + def __init__(self, version: Version): """ - :returns: The iccid - :rtype: unicode - """ - return self._properties['iccid'] + Initialize the SimList - @property - def e_id(self): - """ - :returns: The e_id - :rtype: unicode - """ - return self._properties['e_id'] + :param version: Version that contains the resource - @property - def status(self): - """ - :returns: The status - :rtype: unicode """ - return self._properties['status'] + super().__init__(version) - @property - def commands_callback_url(self): - """ - :returns: The commands_callback_url - :rtype: unicode - """ - return self._properties['commands_callback_url'] + self._uri = "/Sims" - @property - def commands_callback_method(self): + 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]: """ - :returns: The commands_callback_method - :rtype: unicode - """ - return self._properties['commands_callback_method'] + 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_fallback_method(self): - """ - :returns: The sms_fallback_method - :rtype: unicode - """ - return self._properties['sms_fallback_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_url(self): - """ - :returns: The sms_fallback_url - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['sms_fallback_url'] + limits = self._version.read_limits(limit, page_size) + page = self.page( + 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_method(self): - """ - :returns: The sms_method - :rtype: unicode - """ - return self._properties['sms_method'] + return self._version.stream(page, limits["limit"]) - @property - def sms_url(self): - """ - :returns: The sms_url - :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_url'] + 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 voice_fallback_method(self): - """ - :returns: The voice_fallback_method - :rtype: unicode - """ - return self._properties['voice_fallback_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 voice_fallback_url(self): - """ - :returns: The voice_fallback_url - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['voice_fallback_url'] + 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_method(self): - """ - :returns: The voice_method - :rtype: unicode - """ - return self._properties['voice_method'] + return self._version.stream_async(page, limits["limit"]) - @property - def voice_url(self): - """ - :returns: The voice_url - :rtype: unicode + def stream_with_http_info( + 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, + ) -> tuple: """ - return self._properties['voice_url'] + Streams SimInstance and returns headers from first page - @property - def date_created(self): - """ - :returns: The date_created - :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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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 date_updated(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams SimInstance and returns headers from first page + + + :param str status: + :param str iccid: + :param str rate_plan: + :param str e_id: + :param str sim_registration_code: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The date_updated - :rtype: datetime + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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['date_updated'] + 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 url(self): + :param str status: + :param str iccid: + :param str rate_plan: + :param str e_id: + :param str sim_registration_code: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimInstance]: + """ + Asynchronously lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str status: + :param str iccid: + :param str rate_plan: + :param str e_id: + :param str sim_registration_code: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists SimInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists SimInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - :returns: The url - :rtype: unicode + Retrieve a single page of SimInstance records from the API. + Request is executed immediately + + :param status: + :param iccid: + :param rate_plan: + :param e_id: + :param sim_registration_code: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimInstance """ - return self._properties['url'] + data = values.of( + { + "Status": status, + "Iccid": iccid, + "RatePlan": rate_plan, + "EId": e_id, + "SimRegistrationCode": sim_registration_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def links(self): + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with SimPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SimPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with SimPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SimPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 + + :param target_url: API-generated URL for the requested results page - def fetch(self): + :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 - 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): + :param target_url: API-generated URL for the requested results page + + :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..33010acf35 100644 --- a/twilio/rest/preview/wireless/sim/usage.py +++ b/twilio/rest/preview/wireless/sim/usage.py @@ -1,290 +1,353 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource -from twilio.base.page import Page - +from twilio.base.version import Version -class UsageList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - def __init__(self, version, sim_sid): - """ - Initialize the UsageList - - :param Version version: Version that contains the resource - :param sim_sid: The sim_sid - - :returns: twilio.rest.preview.wireless.sim.usage.UsageList - :rtype: twilio.rest.preview.wireless.sim.usage.UsageList - """ - super(UsageList, self).__init__(version) +class UsageInstance(InstanceResource): + """ + :ivar sim_sid: + :ivar sim_unique_name: + :ivar account_sid: + :ivar period: + :ivar commands_usage: + :ivar commands_costs: + :ivar data_usage: + :ivar data_costs: + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): + super().__init__(version) + + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.sim_unique_name: Optional[str] = payload.get("sim_unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.period: Optional[Dict[str, object]] = payload.get("period") + self.commands_usage: Optional[Dict[str, object]] = payload.get("commands_usage") + self.commands_costs: Optional[Dict[str, object]] = payload.get("commands_costs") + self.data_usage: Optional[Dict[str, object]] = payload.get("data_usage") + self.data_costs: Optional[Dict[str, object]] = payload.get("data_costs") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sim_sid": sim_sid, + } - # Path Solution - self._solution = {'sim_sid': sim_sid, } + self._context: Optional[UsageContext] = None - def get(self): + @property + def _proxy(self) -> "UsageContext": """ - Constructs a UsageContext + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.preview.wireless.sim.usage.UsageContext - :rtype: twilio.rest.preview.wireless.sim.usage.UsageContext + :returns: UsageContext for this UsageInstance """ - return UsageContext(self._version, sim_sid=self._solution['sim_sid'], ) + if self._context is None: + self._context = UsageContext( + self._version, + sim_sid=self._solution["sim_sid"], + ) + return self._context - def __call__(self): + def fetch( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> "UsageInstance": """ - Constructs a UsageContext + Fetch the UsageInstance - :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'], ) + :param end: + :param start: - def __repr__(self): + :returns: The fetched UsageInstance """ - Provide a friendly representation + return self._proxy.fetch( + end=end, + start=start, + ) - :returns: Machine friendly representation - :rtype: str + async def fetch_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> "UsageInstance": """ - return '' + Asynchronous coroutine to fetch the UsageInstance + :param end: + :param start: -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. """ + :returns: The fetched UsageInstance + """ + return await self._proxy.fetch_async( + end=end, + start=start, + ) - def __init__(self, version, response, solution): + def fetch_with_http_info( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Initialize the UsagePage + Fetch the UsageInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - super(UsagePage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info( + end=end, + start=start, + ) - def get_instance(self, payload): + async def fetch_with_http_info_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Build an instance of UsageInstance + Asynchronous coroutine to fetch the UsageInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return UsageInstance(self._version, payload, sim_sid=self._solution['sim_sid'], ) + return await self._proxy.fetch_with_http_info_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: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "End": end, + "Start": start, + } + ) + + headers = values.of({}) - def fetch(self, end=values.unset, start=values.unset): + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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._fetch(end=end, start=start) + return UsageInstance( + self._version, + payload, + sim_sid=self._solution["sim_sid"], + ) - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + def fetch_with_http_info( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the UsageInstance and return response metadata - return UsageInstance(self._version, payload, sim_sid=self._solution['sim_sid'], ) + :param end: + :param start: - def __repr__(self): + :returns: ApiResponse with instance, status code, and headers """ - Provide a friendly representation + payload, status_code, headers = self._fetch(end=end, start=start) + instance = UsageInstance( + self._version, + payload, + sim_sid=self._solution["sim_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: Machine friendly representation - :rtype: str + async def _fetch_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> tuple: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Internal async helper for fetch operation + Returns: + tuple: (payload, status_code, headers) + """ -class UsageInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, sim_sid): - """ - Initialize the UsageInstance - - :returns: twilio.rest.preview.wireless.sim.usage.UsageInstance - :rtype: twilio.rest.preview.wireless.sim.usage.UsageInstance - """ - super(UsageInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sim_sid': payload.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'), - } + params = values.of( + { + "End": end, + "Start": start, + } + ) - # Context - self._context = None - self._solution = {'sim_sid': sim_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: 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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - @property - def sim_sid(self): - """ - :returns: The sim_sid - :rtype: unicode + async def fetch_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> UsageInstance: """ - return self._properties['sim_sid'] + Asynchronous coroutine to fetch the UsageInstance - @property - def sim_unique_name(self): - """ - :returns: The sim_unique_name - :rtype: unicode - """ - return self._properties['sim_unique_name'] + :param end: + :param start: - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: The fetched UsageInstance """ - return self._properties['account_sid'] + payload, _, _ = await self._fetch_async(end=end, start=start) + return UsageInstance( + self._version, + payload, + sim_sid=self._solution["sim_sid"], + ) - @property - def period(self): - """ - :returns: The period - :rtype: dict + async def fetch_with_http_info_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['period'] + Asynchronous coroutine to fetch the UsageInstance and return response metadata - @property - def commands_usage(self): - """ - :returns: The commands_usage - :rtype: dict - """ - return self._properties['commands_usage'] + :param end: + :param start: - @property - def commands_costs(self): - """ - :returns: The commands_costs - :rtype: dict + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['commands_costs'] + payload, status_code, headers = await self._fetch_async(end=end, start=start) + instance = UsageInstance( + self._version, + payload, + sim_sid=self._solution["sim_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def data_usage(self): - """ - :returns: The data_usage - :rtype: dict + def __repr__(self) -> str: """ - return self._properties['data_usage'] + Provide a friendly representation - @property - def data_costs(self): + :returns: Machine friendly representation """ - :returns: The data_costs - :rtype: dict + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UsageList(ListResource): + + def __init__(self, version: Version, sim_sid: str): """ - return self._properties['data_costs'] + Initialize the UsageList + + :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..e011a3d2ae --- /dev/null +++ b/twilio/rest/preview_iam/v1/authorize.py @@ -0,0 +1,221 @@ +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.api_response import ApiResponse + +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, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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, + } + ) + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers, params=params + ) + + 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: + """ + 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 + """ + payload, _, _ = self._fetch( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + return AuthorizeInstance(self._version, payload) + + def fetch_with_http_info( + 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, + ) -> ApiResponse: + """ + Fetch the AuthorizeInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + instance = AuthorizeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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, + } + ) + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + 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 + """ + payload, _, _ = await self._fetch_async( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + return AuthorizeInstance(self._version, payload) + + async def fetch_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously fetch the AuthorizeInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + instance = AuthorizeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..9a496553a6 --- /dev/null +++ b/twilio/rest/preview_iam/v1/token.py @@ -0,0 +1,301 @@ +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.api_response import ApiResponse + +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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + 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, + ) + return TokenInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the TokenInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + 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, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + 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, + ) + return TokenInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the TokenInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + 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, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..3ee97bd283 --- /dev/null +++ b/twilio/rest/preview_iam/versionless/organization/account.py @@ -0,0 +1,681 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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["AccountInstance.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AccountInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AccountInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AccountInstance: + """ + Fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + payload, _, _ = self._fetch() + return AccountInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AccountInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AccountInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AccountInstance: + """ + Asynchronous coroutine to fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + payload, _, _ = await self._fetch_async() + return AccountInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AccountInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AccountInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AccountInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AccountInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AccountInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AccountInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AccountPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AccountPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AccountPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AccountPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..860b077723 --- /dev/null +++ b/twilio/rest/preview_iam/versionless/organization/role_assignment.py @@ -0,0 +1,1011 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 + :ivar resource_type: The resource type for resource-level role assignments + :ivar resource_id: The resource id for resource-level role assignments + """ + + 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") + self.resource_type: Optional[str] = payload.get("resource_type") + self.resource_id: Optional[str] = payload.get("resource_id") + + def to_dict(self): + return { + "role_sid": self.role_sid, + "scope": self.scope, + "identity": self.identity, + "resource_type": self.resource_type, + "resource_id": self.resource_id, + } + + """ + :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 resource_type: The resource type for resource-level role assignments + :ivar resource_id: The resource id for resource-level role assignments + :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.resource_type: Optional[str] = payload.get("resource_type") + self.resource_id: Optional[str] = payload.get("resource_id") + 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 + :ivar resource_type: The resource type for resource-level role assignments + :ivar resource_id: The resource id for resource-level role assignments + """ + + 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") + self.resource_type: Optional[str] = payload.get("resource_type") + self.resource_id: Optional[str] = payload.get("resource_id") + + def to_dict(self): + return { + "role_sid": self.role_sid, + "scope": self.scope, + "identity": self.identity, + "resource_type": self.resource_type, + "resource_id": self.resource_id, + } + + 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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the RoleAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleAssignmentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleAssignmentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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 + :ivar resource_type: The resource type for resource-level role assignments + :ivar resource_id: The resource id for resource-level role assignments + """ + + 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") + self.resource_type: Optional[str] = payload.get("resource_type") + self.resource_id: Optional[str] = payload.get("resource_id") + + def to_dict(self): + return { + "role_sid": self.role_sid, + "scope": self.scope, + "identity": self.identity, + "resource_type": self.resource_type, + "resource_id": self.resource_id, + } + + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + public_api_create_role_assignment_request=public_api_create_role_assignment_request + ) + return RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def create_with_http_info( + self, + public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, + ) -> ApiResponse: + """ + Create the RoleAssignmentInstance and return response metadata + + :param public_api_create_role_assignment_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + public_api_create_role_assignment_request=public_api_create_role_assignment_request + ) + instance = RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + public_api_create_role_assignment_request=public_api_create_role_assignment_request + ) + return RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + async def create_with_http_info_async( + self, + public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, + ) -> ApiResponse: + """ + Asynchronously create the RoleAssignmentInstance and return response metadata + + :param public_api_create_role_assignment_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + public_api_create_role_assignment_request=public_api_create_role_assignment_request + ) + instance = RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: 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 str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.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, + resource_type=resource_type, + resource_id=resource_id, + 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, + resource_type: Union[str, object] = values.unset, + resource_id: 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 str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(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, + resource_type=resource_type, + resource_id=resource_id, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RoleAssignmentInstance and returns headers from first page + + + :param str identity: + :param str scope: + :param str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, + scope=scope, + resource_type=resource_type, + resource_id=resource_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RoleAssignmentInstance and returns headers from first page + + + :param str identity: + :param str scope: + :param str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, + scope=scope, + resource_type=resource_type, + resource_id=resource_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: 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 str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + 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, + resource_type=resource_type, + resource_id=resource_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: 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 str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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, + resource_type=resource_type, + resource_id=resource_id, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RoleAssignmentInstance and returns headers from first page + + + :param str identity: + :param str scope: + :param str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + scope=scope, + resource_type=resource_type, + resource_id=resource_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoleAssignmentInstance and returns headers from first page + + + :param str identity: + :param str scope: + :param str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + scope=scope, + resource_type=resource_type, + resource_id=resource_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_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, + ) -> RoleAssignmentPage: + """ + Retrieve a single page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param identity: + :param scope: + :param resource_type: Filter by resource type for resource-level role assignments + :param resource_id: Filter by resource id for resource-level role assignments + :param page_token: PageToken provided by the API + :param page_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, + "ResourceType": resource_type, + "ResourceId": resource_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 RoleAssignmentPage(self._version, response, solution=self._solution) + + async def page_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_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, + ) -> RoleAssignmentPage: + """ + Asynchronously retrieve a single page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param identity: + :param scope: + :param resource_type: Filter by resource type for resource-level role assignments + :param resource_id: Filter by resource id for resource-level role assignments + :param page_token: PageToken provided by the API + :param page_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, + "ResourceType": resource_type, + "ResourceId": resource_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 RoleAssignmentPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param identity: + :param scope: + :param resource_type: Filter by resource type for resource-level role assignments + :param resource_id: Filter by resource id for resource-level role assignments + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RoleAssignmentPage, status code, and headers + """ + data = values.of( + { + "Identity": identity, + "Scope": scope, + "ResourceType": resource_type, + "ResourceId": resource_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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RoleAssignmentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param identity: + :param scope: + :param resource_type: Filter by resource type for resource-level role assignments + :param resource_id: Filter by resource id for resource-level role assignments + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RoleAssignmentPage, status code, and headers + """ + data = values.of( + { + "Identity": identity, + "Scope": scope, + "ResourceType": resource_type, + "ResourceId": resource_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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RoleAssignmentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..8299913b2c --- /dev/null +++ b/twilio/rest/preview_iam/versionless/organization/user.py @@ -0,0 +1,1830 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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("resourceType") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("lastModified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + "resourceType": self.resource_type, + "created": self.created, + "lastModified": 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("givenName") + self.family_name: Optional[str] = payload.get("familyName") + + def to_dict(self): + return { + "givenName": self.given_name, + "familyName": self.family_name, + } + + class ScimPatchOperation(object): + """ + :ivar op: The operation to perform + :ivar path: + :ivar value: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.op: Optional[str] = payload.get("op") + self.path: Optional[str] = payload.get("path") + self.value: Optional[Dict[str, object]] = payload.get("value") + + def to_dict(self): + return { + "op": self.op, + "path": self.path, + "value": self.value, + } + + class ScimPatchRequest(object): + """ + :ivar schemas: + :ivar operations: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.schemas: Optional[List[str]] = payload.get("schemas") + self.operations: Optional[List[UserList.ScimPatchOperation]] = payload.get( + "Operations" + ) + + def to_dict(self): + return { + "schemas": self.schemas, + "Operations": ( + [operations.to_dict() for operations in self.operations] + if self.operations is not None + else None + ), + } + + 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("externalId") + self.user_name: Optional[str] = payload.get("userName") + self.display_name: Optional[str] = payload.get("displayName") + 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["UserInstance.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") + + 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["UserInstance.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def patch( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Patch the UserInstance + + :param scim_patch_request: + :param if_match: + + :returns: The patched UserInstance + """ + return self._proxy.patch( + scim_patch_request=scim_patch_request, + if_match=if_match, + ) + + async def patch_async( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to patch the UserInstance + + :param scim_patch_request: + :param if_match: + + :returns: The patched UserInstance + """ + return await self._proxy.patch_async( + scim_patch_request=scim_patch_request, + if_match=if_match, + ) + + 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 update_with_http_info( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param scim_user: + :param if_match: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + scim_user=scim_user, + if_match=if_match, + ) + + async def update_with_http_info_async( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param scim_user: + :param if_match: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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("resourceType") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("lastModified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + "resourceType": self.resource_type, + "created": self.created, + "lastModified": 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("givenName") + self.family_name: Optional[str] = payload.get("familyName") + + def to_dict(self): + return { + "givenName": self.given_name, + "familyName": self.family_name, + } + + class ScimPatchOperation(object): + """ + :ivar op: The operation to perform + :ivar path: + :ivar value: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.op: Optional[str] = payload.get("op") + self.path: Optional[str] = payload.get("path") + self.value: Optional[Dict[str, object]] = payload.get("value") + + def to_dict(self): + return { + "op": self.op, + "path": self.path, + "value": self.value, + } + + class ScimPatchRequest(object): + """ + :ivar schemas: + :ivar operations: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.schemas: Optional[List[str]] = payload.get("schemas") + self.operations: Optional[List[UserList.ScimPatchOperation]] = payload.get( + "Operations" + ) + + def to_dict(self): + return { + "schemas": self.schemas, + "Operations": ( + [operations.to_dict() for operations in self.operations] + if self.operations is not None + else None + ), + } + + 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("externalId") + self.user_name: Optional[str] = payload.get("userName") + self.display_name: Optional[str] = payload.get("displayName") + 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["UserInstance.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") + + 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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = scim_patch_request.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" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Patch the UserInstance + + :param scim_patch_request: + :param if_match: + + :returns: The patched UserInstance + """ + payload, _, _ = self._patch( + scim_patch_request=scim_patch_request, if_match=if_match + ) + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + def patch_with_http_info( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Patch the UserInstance and return response metadata + + :param scim_patch_request: + :param if_match: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch( + scim_patch_request=scim_patch_request, if_match=if_match + ) + instance = UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = scim_patch_request.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" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to patch the UserInstance + + :param scim_patch_request: + :param if_match: + + :returns: The patched UserInstance + """ + payload, _, _ = await self._patch_async( + scim_patch_request=scim_patch_request, if_match=if_match + ) + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + async def patch_with_http_info_async( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the UserInstance and return response metadata + + :param scim_patch_request: + :param if_match: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + scim_patch_request=scim_patch_request, if_match=if_match + ) + instance = UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(scim_user=scim_user, if_match=if_match) + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + def update_with_http_info( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the UserInstance and return response metadata + + :param scim_user: + :param if_match: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + scim_user=scim_user, if_match=if_match + ) + instance = UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(scim_user=scim_user, if_match=if_match) + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + async def update_with_http_info_async( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance and return response metadata + + :param scim_user: + :param if_match: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + scim_user=scim_user, if_match=if_match + ) + instance = UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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("resourceType") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("lastModified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + "resourceType": self.resource_type, + "created": self.created, + "lastModified": 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("givenName") + self.family_name: Optional[str] = payload.get("familyName") + + def to_dict(self): + return { + "givenName": self.given_name, + "familyName": self.family_name, + } + + class ScimPatchOperation(object): + """ + :ivar op: The operation to perform + :ivar path: + :ivar value: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.op: Optional[str] = payload.get("op") + self.path: Optional[str] = payload.get("path") + self.value: Optional[Dict[str, object]] = payload.get("value") + + def to_dict(self): + return { + "op": self.op, + "path": self.path, + "value": self.value, + } + + class ScimPatchRequest(object): + """ + :ivar schemas: + :ivar operations: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.schemas: Optional[List[str]] = payload.get("schemas") + self.operations: Optional[List[UserList.ScimPatchOperation]] = payload.get( + "Operations" + ) + + def to_dict(self): + return { + "schemas": self.schemas, + "Operations": ( + [operations.to_dict() for operations in self.operations] + if self.operations is not None + else None + ), + } + + 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("externalId") + self.user_name: Optional[str] = payload.get("userName") + self.display_name: Optional[str] = payload.get("displayName") + 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["UserInstance.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") + + 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, scim_user: ScimUser) -> UserInstance: + """ + Create the UserInstance + + :param scim_user: + + :returns: The created UserInstance + """ + payload, _, _ = self._create(scim_user=scim_user) + return UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def create_with_http_info(self, scim_user: ScimUser) -> ApiResponse: + """ + Create the UserInstance and return response metadata + + :param scim_user: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(scim_user=scim_user) + instance = UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, scim_user: ScimUser) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, scim_user: ScimUser) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param scim_user: + + :returns: The created UserInstance + """ + payload, _, _ = await self._create_async(scim_user=scim_user) + return UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + async def create_with_http_info_async(self, scim_user: ScimUser) -> ApiResponse: + """ + Asynchronously create the UserInstance and return response metadata + + :param scim_user: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(scim_user=scim_user) + instance = UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + filter=filter, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + filter=filter, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + filter=filter, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + filter=filter, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with UserPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with UserPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 eef5ea8f1f..ecb387919d 100644 --- a/twilio/rest/pricing/v1/messaging/country.py +++ b/twilio/rest/pricing/v1/messaging/country.py @@ -1,327 +1,656 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +class CountryInstance(InstanceResource): + """ + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar outbound_sms_prices: The list of [OutboundSMSPrice](https://www.twilio.com/docs/sms/api/pricing#outbound-sms-price) records that represent the price to send a message for each MCC/MNC applicable in this country. + :ivar inbound_sms_prices: The list of [InboundPrice](https://www.twilio.com/docs/sms/api/pricing#inbound-price) records that describe the price to receive an inbound SMS to the different Twilio phone number types supported in this country + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + iso_country: Optional[str] = None, + ): + super().__init__(version) + + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.outbound_sms_prices: Optional[List[str]] = payload.get( + "outbound_sms_prices" + ) + self.inbound_sms_prices: Optional[List[str]] = payload.get("inbound_sms_prices") + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "iso_country": iso_country or self.iso_country, + } - def __init__(self, version): + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": """ - Initialize the CountryList + 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: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_country=self._solution["iso_country"], + ) + return self._context - :returns: twilio.rest.pricing.v1.messaging.country.CountryList - :rtype: twilio.rest.pricing.v1.messaging.country.CountryList + def fetch(self) -> "CountryInstance": """ - super(CountryList, self).__init__(version) + Fetch the CountryInstance - # Path Solution - self._solution = {} - self._uri = '/Messaging/Countries'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance - :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 await self._proxy.fetch_async() - page = self.page(page_size=limits['page_size'], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with instance, status code, and headers """ - 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 self._proxy.fetch_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.pricing.v1.messaging.country.CountryInstance] + + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_with_http_info_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 CountryInstance 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 str page_token: PageToken provided by the API - :param int page_number: 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) -> tuple: """ - Retrieve a specific page of CountryInstance records from the API. - Request is executed immediately + Internal helper for fetch operation - :param str target_url: API-generated URL for the requested results page + Returns: + tuple: (payload, status_code, headers) + """ - :returns: Page of CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryPage + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CountryInstance: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + payload, _, _ = self._fetch() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], ) - return CountryPage(self._version, response, self._solution) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance and return response metadata + - def get(self, iso_country): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a CountryContext + payload, status_code, headers = self._fetch() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param iso_country: The ISO country code + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: twilio.rest.pricing.v1.messaging.country.CountryContext - :rtype: twilio.rest.pricing.v1.messaging.country.CountryContext + Returns: + tuple: (payload, status_code, headers) """ - return CountryContext(self._version, iso_country=iso_country, ) - def __call__(self, iso_country): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + 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, ) + payload, _, _ = await self._fetch_async() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance and return response metadata - def __repr__(self): + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class CountryPage(Page): - """ """ - def __init__(self, version, response, solution): + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: + """ + Build an instance of CountryInstance + + :param payload: Payload response from the API """ - Initialize the CountryPage - :param Version version: Version that contains the resource - :param Response response: Response from the API + return CountryInstance(self._version, payload) - :returns: twilio.rest.pricing.v1.messaging.country.CountryPage - :rtype: twilio.rest.pricing.v1.messaging.country.CountryPage + def __repr__(self) -> str: """ - super(CountryPage, self).__init__(version, response) + Provide a friendly representation - # Path Solution - self._solution = solution + :returns: Machine friendly representation + """ + return "" + + +class CountryList(ListResource): - def get_instance(self, payload): + def __init__(self, version: Version): """ - Build an instance of CountryInstance + Initialize the CountryList - :param dict payload: Payload response from the API + :param version: Version that contains the resource - :returns: twilio.rest.pricing.v1.messaging.country.CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryInstance """ - return CountryInstance(self._version, payload, ) + super().__init__(version) - def __repr__(self): + self._uri = "/Messaging/Countries" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: """ - Provide a friendly representation + 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 """ - return '' + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + return self._version.stream(page, limits["limit"]) -class CountryContext(InstanceContext): - """ """ + 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) - def __init__(self, version, iso_country): + :returns: Generator that will yield up to limit results """ - Initialize the CountryContext + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :param Version version: Version that contains the resource - :param iso_country: The ISO country code + return self._version.stream_async(page, limits["limit"]) - :returns: twilio.rest.pricing.v1.messaging.country.CountryContext - :rtype: twilio.rest.pricing.v1.messaging.country.CountryContext + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(CountryContext, self).__init__(version) + Streams CountryInstance and returns headers from first page - # Path Solution - self._solution = {'iso_country': iso_country, } - self._uri = '/Messaging/Countries/{iso_country}'.format(**self._solution) - 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: tuple of (generator, status_code, headers) where generator yields instances """ - Fetch the CountryInstance + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: The fetched CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryInstance + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronously streams CountryInstance and returns headers from first page - return CountryInstance(self._version, payload, iso_country=self._solution['iso_country'], ) - 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: tuple of (generator, status_code, headers) where generator yields instances """ - Provide a friendly representation + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :returns: Machine friendly representation - :rtype: str + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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) -class CountryInstance(InstanceResource): - """ """ + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - def __init__(self, version, payload, iso_country=None): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: """ - Initialize the 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. - :returns: twilio.rest.pricing.v1.messaging.country.CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryInstance + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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(CountryInstance, self).__init__(version) - # 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'), - } + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - # Context - self._context = None - self._solution = {'iso_country': iso_country or self._properties['iso_country'], } + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CountryInstance and returns headers from first page - @property - def _proxy(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: ApiResponse with list of instances, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: CountryContext for this CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryContext + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - if self._context is None: - self._context = CountryContext(self._version, iso_country=self._solution['iso_country'], ) - return self._context + Asynchronously lists CountryInstance and returns headers from first page - @property - def 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: ApiResponse with list of instances, status code, and headers """ - :returns: The name of the country - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['country'] + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately - @property - def iso_country(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 CountryInstance """ - :returns: The ISO country code - :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 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: """ - return self._properties['iso_country'] + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately - @property - def outbound_sms_prices(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 CountryInstance """ - :returns: The list of OutboundSMSPrice records - :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 CountryPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['outbound_sms_prices'] + Retrieve a single page with response metadata - @property - def inbound_sms_prices(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: ApiResponse with CountryPage, status code, and headers """ - :returns: The list of InboundPrice records - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['inbound_sms_prices'] + Asynchronously retrieve a single page with response metadata - @property - def price_unit(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: ApiResponse with CountryPage, status code, and headers """ - :returns: The currency in which prices are measured, in ISO 4127 format (e.g. usd, eur, jpy) - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> CountryPage: """ - return self._properties['price_unit'] + Retrieve a specific page of CountryInstance 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 CountryInstance """ - :returns: The absolute URL of the resource - :rtype: unicode + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CountryPage: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of CountryInstance """ - Fetch the CountryInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) - :returns: The fetched CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryInstance + def get(self, iso_country: str) -> CountryContext: """ - return self._proxy.fetch() + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __call__(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 38bdac57e2..7775696a6d 100644 --- a/twilio/rest/pricing/v1/phone_number/country.py +++ b/twilio/rest/pricing/v1/phone_number/country.py @@ -1,318 +1,654 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +class CountryInstance(InstanceResource): + """ + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar phone_number_prices: The list of [PhoneNumberPrice](https://www.twilio.com/docs/phone-numbers/pricing#phone-number-price) records. + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + iso_country: Optional[str] = None, + ): + super().__init__(version) + + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.phone_number_prices: Optional[List[str]] = payload.get( + "phone_number_prices" + ) + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "iso_country": iso_country or self.iso_country, + } - def __init__(self, version): + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": """ - Initialize the CountryList + 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: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_country=self._solution["iso_country"], + ) + return self._context - :returns: twilio.rest.pricing.v1.phone_number.country.CountryList - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryList + def fetch(self) -> "CountryInstance": """ - super(CountryList, self).__init__(version) + Fetch the CountryInstance - # Path Solution - self._solution = {} - self._uri = '/PhoneNumbers/Countries'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance - :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 await self._proxy.fetch_async() - page = self.page(page_size=limits['page_size'], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with instance, status code, and headers """ - 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 self._proxy.fetch_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.pricing.v1.phone_number.country.CountryInstance] + + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_with_http_info_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 CountryInstance 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 str page_token: PageToken provided by the API - :param int page_number: 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) -> tuple: """ - Retrieve a specific page of CountryInstance records from the API. - Request is executed immediately + Internal helper for fetch operation - :param str target_url: API-generated URL for the requested results page + Returns: + tuple: (payload, status_code, headers) + """ - :returns: Page of CountryInstance - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryPage + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CountryInstance: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + payload, _, _ = self._fetch() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], ) - return CountryPage(self._version, response, self._solution) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance and return response metadata + - def get(self, iso_country): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a CountryContext + payload, status_code, headers = self._fetch() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param iso_country: The ISO country code + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: twilio.rest.pricing.v1.phone_number.country.CountryContext - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryContext + Returns: + tuple: (payload, status_code, headers) """ - return CountryContext(self._version, iso_country=iso_country, ) - def __call__(self, iso_country): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CountryInstance: """ - Constructs a CountryContext + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + payload, _, _ = await self._fetch_async() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return CountryContext(self._version, iso_country=iso_country, ) + payload, status_code, headers = await self._fetch_async() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 CountryPage(Page): - """ """ - def __init__(self, version, response, solution): + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: + """ + Build an instance of CountryInstance + + :param payload: Payload response from the API """ - Initialize the CountryPage - :param Version version: Version that contains the resource - :param Response response: Response from the API + return CountryInstance(self._version, payload) - :returns: twilio.rest.pricing.v1.phone_number.country.CountryPage - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryPage + def __repr__(self) -> str: """ - super(CountryPage, self).__init__(version, response) + Provide a friendly representation - # Path Solution - self._solution = solution + :returns: Machine friendly representation + """ + return "" + + +class CountryList(ListResource): - def get_instance(self, payload): + def __init__(self, version: Version): """ - Build an instance of CountryInstance + Initialize the CountryList - :param dict payload: Payload response from the API + :param version: Version that contains the resource - :returns: twilio.rest.pricing.v1.phone_number.country.CountryInstance - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryInstance """ - return CountryInstance(self._version, payload, ) + super().__init__(version) - def __repr__(self): + self._uri = "/PhoneNumbers/Countries" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: """ - Provide a friendly representation + 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 """ - return '' + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + return self._version.stream(page, limits["limit"]) -class CountryContext(InstanceContext): - """ """ + 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. - def __init__(self, version, iso_country): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - Initialize the CountryContext + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :param Version version: Version that contains the resource - :param iso_country: The ISO country code + return self._version.stream_async(page, limits["limit"]) - :returns: twilio.rest.pricing.v1.phone_number.country.CountryContext - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryContext + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(CountryContext, self).__init__(version) + Streams CountryInstance and returns headers from first page - # Path Solution - self._solution = {'iso_country': iso_country, } - self._uri = '/PhoneNumbers/Countries/{iso_country}'.format(**self._solution) - 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: tuple of (generator, status_code, headers) where generator yields instances """ - Fetch the CountryInstance + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: The fetched CountryInstance - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryInstance + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CountryInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - return CountryInstance(self._version, payload, iso_country=self._solution['iso_country'], ) + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - def __repr__(self): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: """ - Provide a friendly representation + Lists CountryInstance 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, + ) + ) -class CountryInstance(InstanceResource): - """ """ + 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) - def __init__(self, version, payload, iso_country=None): + :returns: list that will contain up to limit results """ - Initialize the CountryInstance - :returns: twilio.rest.pricing.v1.phone_number.country.CountryInstance - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryInstance + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - super(CountryInstance, self).__init__(version) + Lists CountryInstance and returns headers from first page - # 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'), - } - # Context - self._context = None - self._solution = {'iso_country': iso_country or self._properties['iso_country'], } + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 _proxy(self): + :returns: ApiResponse with list of instances, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: CountryContext for this CountryInstance - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryContext + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - if self._context is None: - self._context = CountryContext(self._version, iso_country=self._solution['iso_country'], ) - return self._context + Asynchronously lists CountryInstance and returns headers from first page - @property - def 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: ApiResponse with list of instances, status code, and headers """ - :returns: The name of the country - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['country'] + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately - @property - def iso_country(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 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: """ - :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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The list of PhoneNumberPrices records - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers """ - return self._properties['phone_number_prices'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def price_unit(self): + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers """ - :returns: The currency in which prices are measured, in ISO 4127 format (e.g. usd, eur, jpy) - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> CountryPage: """ - return self._properties['price_unit'] + Retrieve a specific page of CountryInstance 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 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: """ - :returns: The absolute URL of the resource - :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['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) - def fetch(self): + def get(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 __call__(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 81d67ac7f4..600488ab44 100644 --- a/twilio/rest/pricing/v1/voice/country.py +++ b/twilio/rest/pricing/v1/voice/country.py @@ -1,327 +1,658 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +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") - def __init__(self, version): + self._solution = { + "iso_country": iso_country or self.iso_country, + } + + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": """ - Initialize the CountryList + 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: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_country=self._solution["iso_country"], + ) + return self._context - :returns: twilio.rest.pricing.v1.voice.country.CountryList - :rtype: twilio.rest.pricing.v1.voice.country.CountryList + def fetch(self) -> "CountryInstance": """ - super(CountryList, self).__init__(version) + Fetch the CountryInstance - # Path Solution - self._solution = {} - self._uri = '/Voice/Countries'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance - :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 await self._proxy.fetch_async() - page = self.page(page_size=limits['page_size'], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with instance, status code, and headers """ - 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 self._proxy.fetch_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.pricing.v1.voice.country.CountryInstance] + + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_with_http_info_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 CountryInstance 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 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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - Retrieve a specific page of CountryInstance records from the API. - Request is executed immediately - :param str target_url: API-generated URL for the requested results page + headers = values.of({}) - :returns: Page of CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryPage + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CountryInstance: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + payload, _, _ = self._fetch() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], ) - return CountryPage(self._version, response, self._solution) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance and return response metadata + - def get(self, iso_country): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a CountryContext + payload, status_code, headers = self._fetch() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param iso_country: The ISO country code + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: twilio.rest.pricing.v1.voice.country.CountryContext - :rtype: twilio.rest.pricing.v1.voice.country.CountryContext + Returns: + tuple: (payload, status_code, headers) """ - return CountryContext(self._version, iso_country=iso_country, ) - def __call__(self, iso_country): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CountryInstance: """ - Constructs a CountryContext + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + payload, _, _ = await self._fetch_async() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance and return response metadata - :param iso_country: The ISO country code - :returns: twilio.rest.pricing.v1.voice.country.CountryContext - :rtype: twilio.rest.pricing.v1.voice.country.CountryContext + :returns: ApiResponse with instance, status code, and headers """ - return CountryContext(self._version, iso_country=iso_country, ) + payload, status_code, headers = await self._fetch_async() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 CountryPage(Page): - """ """ - def __init__(self, version, response, solution): + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ - Initialize the CountryPage + Build an instance of CountryInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API + :param payload: Payload response from the API + """ - :returns: twilio.rest.pricing.v1.voice.country.CountryPage - :rtype: twilio.rest.pricing.v1.voice.country.CountryPage + return CountryInstance(self._version, payload) + + def __repr__(self) -> str: """ - super(CountryPage, self).__init__(version, response) + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" - # Path Solution - self._solution = solution - def get_instance(self, payload): +class CountryList(ListResource): + + def __init__(self, version: Version): """ - Build an instance of CountryInstance + Initialize the CountryList - :param dict payload: Payload response from the API + :param version: Version that contains the resource - :returns: twilio.rest.pricing.v1.voice.country.CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryInstance """ - return CountryInstance(self._version, payload, ) + super().__init__(version) + + self._uri = "/Voice/Countries" - def __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: """ - Provide a friendly representation + 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 """ - return '' + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + return self._version.stream(page, limits["limit"]) -class CountryContext(InstanceContext): - """ """ + 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) - def __init__(self, version, iso_country): + :returns: Generator that will yield up to limit results """ - Initialize the CountryContext + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :param Version version: Version that contains the resource - :param iso_country: The ISO country code + return self._version.stream_async(page, limits["limit"]) - :returns: twilio.rest.pricing.v1.voice.country.CountryContext - :rtype: twilio.rest.pricing.v1.voice.country.CountryContext + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(CountryContext, self).__init__(version) + Streams CountryInstance and returns headers from first page - # Path Solution - self._solution = {'iso_country': iso_country, } - self._uri = '/Voice/Countries/{iso_country}'.format(**self._solution) - 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: tuple of (generator, status_code, headers) where generator yields instances """ - Fetch the CountryInstance + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: The fetched CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryInstance + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronously streams CountryInstance and returns headers from first page - return CountryInstance(self._version, payload, iso_country=self._solution['iso_country'], ) - 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: tuple of (generator, status_code, headers) where generator yields instances """ - Provide a friendly representation + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :returns: Machine friendly representation - :rtype: str + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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) -class CountryInstance(InstanceResource): - """ """ + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - def __init__(self, version, payload, iso_country=None): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: """ - Initialize the 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. - :returns: twilio.rest.pricing.v1.voice.country.CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryInstance + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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(CountryInstance, self).__init__(version) - # 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'), - } + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - # Context - self._context = None - self._solution = {'iso_country': iso_country or self._properties['iso_country'], } + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CountryInstance and returns headers from first page - @property - def _proxy(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: ApiResponse with list of instances, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: CountryContext for this CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryContext + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - if self._context is None: - self._context = CountryContext(self._version, iso_country=self._solution['iso_country'], ) - return self._context + Asynchronously lists CountryInstance and returns headers from first page - @property - def 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: ApiResponse with list of instances, status code, and headers """ - :returns: The name of the country - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['country'] + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately - @property - def iso_country(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 CountryInstance """ - :returns: The ISO country code - :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 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: """ - return self._properties['iso_country'] + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately - @property - def outbound_prefix_prices(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 CountryInstance """ - :returns: The list of OutboundPrefixPrice records - :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 CountryPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['outbound_prefix_prices'] + Retrieve a single page with response metadata - @property - def inbound_call_prices(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: ApiResponse with CountryPage, status code, and headers """ - :returns: The list of InboundCallPrice records - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['inbound_call_prices'] + Asynchronously retrieve a single page with response metadata - @property - def price_unit(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: ApiResponse with CountryPage, status code, and headers """ - :returns: The currency in which prices are measured, in ISO 4127 format (e.g. usd, eur, jpy) - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> CountryPage: """ - return self._properties['price_unit'] + Retrieve a specific page of CountryInstance 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 CountryInstance """ - :returns: The absolute URL of the resource - :rtype: unicode + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CountryPage: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of CountryInstance """ - Fetch the CountryInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) - :returns: The fetched CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryInstance + def get(self, iso_country: str) -> CountryContext: """ - return self._proxy.fetch() + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __call__(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..5dab5e2dd0 100644 --- a/twilio/rest/pricing/v1/voice/number.py +++ b/twilio/rest/pricing/v1/voice/number.py @@ -1,258 +1,265 @@ -# 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.api_response import ApiResponse 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): - """ """ - def __init__(self, version): - """ - Initialize the NumberList +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, + } - :param Version version: Version that contains the resource + self._context: Optional[NumberContext] = None - :returns: twilio.rest.pricing.v1.voice.number.NumberList - :rtype: twilio.rest.pricing.v1.voice.number.NumberList - """ - super(NumberList, self).__init__(version) - - # Path Solution - self._solution = {} - - def get(self, number): + @property + def _proxy(self) -> "NumberContext": """ - Constructs a NumberContext - - :param number: The phone number to fetch + 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.NumberContext - :rtype: twilio.rest.pricing.v1.voice.number.NumberContext + :returns: NumberContext for this NumberInstance """ - return NumberContext(self._version, number=number, ) + if self._context is None: + self._context = NumberContext( + self._version, + number=self._solution["number"], + ) + return self._context - def __call__(self, number): + def fetch(self) -> "NumberInstance": """ - Constructs a NumberContext - - :param number: The phone number to fetch + Fetch the NumberInstance - :returns: twilio.rest.pricing.v1.voice.number.NumberContext - :rtype: twilio.rest.pricing.v1.voice.number.NumberContext - """ - return NumberContext(self._version, number=number, ) - def __repr__(self): + :returns: The fetched NumberInstance """ - Provide a friendly representation + return self._proxy.fetch() - :returns: Machine friendly representation - :rtype: str + async def fetch_async(self) -> "NumberInstance": """ - return '' + Asynchronous coroutine to fetch the NumberInstance -class NumberPage(Page): - """ """ + :returns: The fetched NumberInstance + """ + return await self._proxy.fetch_async() - def __init__(self, version, response, solution): + def fetch_with_http_info(self) -> ApiResponse: """ - Initialize the NumberPage + Fetch the NumberInstance with HTTP info - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.pricing.v1.voice.number.NumberPage - :rtype: twilio.rest.pricing.v1.voice.number.NumberPage + :returns: ApiResponse with instance, status code, and headers """ - super(NumberPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info() - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of NumberInstance + Asynchronous coroutine to fetch the NumberInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return NumberInstance(self._version, payload, ) + return await self._proxy.fetch_with_http_info_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 NumberContext(InstanceContext): - """ """ - def __init__(self, version, number): + def __init__(self, version: Version, number: str): """ Initialize the NumberContext - :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 + :param version: Version that contains the resource + :param number: The phone number to fetch. """ - super(NumberContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'number': number, } - self._uri = '/Voice/Numbers/{number}'.format(**self._solution) + self._solution = { + "number": number, + } + self._uri = "/Voice/Numbers/{number}".format(**self._solution) - def fetch(self): + def _fetch(self) -> tuple: """ - Fetch the NumberInstance + Internal helper for fetch operation - :returns: The fetched NumberInstance - :rtype: twilio.rest.pricing.v1.voice.number.NumberInstance + Returns: + tuple: (payload, status_code, headers) """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return NumberInstance(self._version, payload, number=self._solution['number'], ) + 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) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> NumberInstance: + """ + Fetch the NumberInstance -class NumberInstance(InstanceResource): - """ """ - def __init__(self, version, payload, number=None): + :returns: The fetched NumberInstance """ - Initialize the NumberInstance + payload, _, _ = self._fetch() + return NumberInstance( + self._version, + payload, + number=self._solution["number"], + ) - :returns: twilio.rest.pricing.v1.voice.number.NumberInstance - :rtype: twilio.rest.pricing.v1.voice.number.NumberInstance + def fetch_with_http_info(self) -> ApiResponse: """ - 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'), - } + Fetch the NumberInstance and return response metadata - # Context - self._context = None - self._solution = {'number': number or self._properties['number'], } - @property - def _proxy(self): + :returns: ApiResponse with instance, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, status_code, headers = self._fetch() + instance = NumberInstance( + self._version, + payload, + number=self._solution["number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: NumberContext for this NumberInstance - :rtype: twilio.rest.pricing.v1.voice.number.NumberContext + async def _fetch_async(self) -> tuple: """ - if self._context is None: - self._context = NumberContext(self._version, number=self._solution['number'], ) - return self._context + Internal async helper for fetch operation - @property - def number(self): - """ - :returns: The phone number - :rtype: unicode + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['number'] - @property - def country(self): - """ - :returns: The name of the country - :rtype: unicode - """ - return self._properties['country'] + headers = values.of({}) - @property - def iso_country(self): + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> NumberInstance: """ - :returns: The ISO country code - :rtype: unicode + Asynchronous coroutine to fetch the NumberInstance + + + :returns: The fetched NumberInstance """ - return self._properties['iso_country'] + payload, _, _ = await self._fetch_async() + return NumberInstance( + self._version, + payload, + number=self._solution["number"], + ) - @property - def outbound_call_price(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: The OutboundCallPrice record - :rtype: unicode + Asynchronous coroutine to fetch the NumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['outbound_call_price'] + payload, status_code, headers = await self._fetch_async() + instance = NumberInstance( + self._version, + payload, + number=self._solution["number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def inbound_call_price(self): + def __repr__(self) -> str: """ - :returns: The InboundCallPrice record - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['inbound_call_price'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def price_unit(self): + +class NumberList(ListResource): + + def __init__(self, version: Version): """ - :returns: The currency in which prices are measured, in ISO 4127 format (e.g. usd, eur, jpy) - :rtype: unicode + Initialize the NumberList + + :param version: Version that contains the resource + """ - return self._properties['price_unit'] + super().__init__(version) - @property - def url(self): + def get(self, number: str) -> NumberContext: """ - :returns: The absolute URL of the resource - :rtype: unicode + Constructs a NumberContext + + :param number: The phone number to fetch. """ - return self._properties['url'] + return NumberContext(self._version, number=number) - def fetch(self): + def __call__(self, number: str) -> NumberContext: """ - Fetch 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..94cdd8a272 --- /dev/null +++ b/twilio/rest/pricing/v2/country.py @@ -0,0 +1,658 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + payload, _, _ = self._fetch() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + payload, _, _ = await self._fetch_async() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CountryInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CountryInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..eddd2b6ef5 --- /dev/null +++ b/twilio/rest/pricing/v2/number.py @@ -0,0 +1,324 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the NumberInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + origination_number=origination_number, + ) + + async def fetch_with_http_info_async( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NumberInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "OriginationNumber": origination_number, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = self._fetch(origination_number=origination_number) + return NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + + def fetch_with_http_info( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the NumberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + origination_number=origination_number + ) + instance = NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "OriginationNumber": origination_number, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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 + """ + payload, _, _ = await self._fetch_async(origination_number=origination_number) + return NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + + async def fetch_with_http_info_async( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NumberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + origination_number=origination_number + ) + instance = NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 868b595694..303e8d8522 100644 --- a/twilio/rest/pricing/v2/voice/country.py +++ b/twilio/rest/pricing/v2/voice/country.py @@ -1,327 +1,658 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +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") - def __init__(self, version): + self._solution = { + "iso_country": iso_country or self.iso_country, + } + + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": """ - Initialize the CountryList + 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: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_country=self._solution["iso_country"], + ) + return self._context - :returns: twilio.rest.pricing.v2.voice.country.CountryList - :rtype: twilio.rest.pricing.v2.voice.country.CountryList + def fetch(self) -> "CountryInstance": """ - super(CountryList, self).__init__(version) + Fetch the CountryInstance - # Path Solution - self._solution = {} - self._uri = '/Voice/Countries'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance - :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 await self._proxy.fetch_async() - page = self.page(page_size=limits['page_size'], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with instance, status code, and headers """ - 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 self._proxy.fetch_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.pricing.v2.voice.country.CountryInstance] + + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_with_http_info_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 CountryInstance 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 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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - Retrieve a specific page of CountryInstance records from the API. - Request is executed immediately - :param str target_url: API-generated URL for the requested results page + headers = values.of({}) - :returns: Page of CountryInstance - :rtype: twilio.rest.pricing.v2.voice.country.CountryPage + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CountryInstance: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + payload, _, _ = self._fetch() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], ) - return CountryPage(self._version, response, self._solution) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance and return response metadata + - def get(self, iso_country): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a CountryContext + payload, status_code, headers = self._fetch() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param iso_country: The ISO country code of the pricing information to fetch + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: twilio.rest.pricing.v2.voice.country.CountryContext - :rtype: twilio.rest.pricing.v2.voice.country.CountryContext + Returns: + tuple: (payload, status_code, headers) """ - return CountryContext(self._version, iso_country=iso_country, ) - def __call__(self, iso_country): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CountryInstance: """ - Constructs a CountryContext + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + payload, _, _ = await self._fetch_async() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return CountryContext(self._version, iso_country=iso_country, ) + payload, status_code, headers = await self._fetch_async() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 CountryPage(Page): - """ """ - def __init__(self, version, response, solution): + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ - Initialize the CountryPage + Build an instance of CountryInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API + :param payload: Payload response from the API + """ - :returns: twilio.rest.pricing.v2.voice.country.CountryPage - :rtype: twilio.rest.pricing.v2.voice.country.CountryPage + return CountryInstance(self._version, payload) + + def __repr__(self) -> str: """ - super(CountryPage, self).__init__(version, response) + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" - # Path Solution - self._solution = solution - def get_instance(self, payload): +class CountryList(ListResource): + + def __init__(self, version: Version): """ - Build an instance of CountryInstance + Initialize the CountryList - :param dict payload: Payload response from the API + :param version: Version that contains the resource - :returns: twilio.rest.pricing.v2.voice.country.CountryInstance - :rtype: twilio.rest.pricing.v2.voice.country.CountryInstance """ - return CountryInstance(self._version, payload, ) + super().__init__(version) + + self._uri = "/Voice/Countries" - def __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: """ - Provide a friendly representation + 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 """ - return '' + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + return self._version.stream(page, limits["limit"]) -class CountryContext(InstanceContext): - """ """ + 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) - def __init__(self, version, iso_country): + :returns: Generator that will yield up to limit results """ - Initialize the CountryContext + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :param Version version: Version that contains the resource - :param iso_country: The ISO country code of the pricing information to fetch + return self._version.stream_async(page, limits["limit"]) - :returns: twilio.rest.pricing.v2.voice.country.CountryContext - :rtype: twilio.rest.pricing.v2.voice.country.CountryContext + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(CountryContext, self).__init__(version) + Streams CountryInstance and returns headers from first page - # Path Solution - self._solution = {'iso_country': iso_country, } - self._uri = '/Voice/Countries/{iso_country}'.format(**self._solution) - 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: tuple of (generator, status_code, headers) where generator yields instances """ - Fetch the CountryInstance + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: The fetched CountryInstance - :rtype: twilio.rest.pricing.v2.voice.country.CountryInstance + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronously streams CountryInstance and returns headers from first page - return CountryInstance(self._version, payload, iso_country=self._solution['iso_country'], ) - 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: tuple of (generator, status_code, headers) where generator yields instances """ - Provide a friendly representation + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :returns: Machine friendly representation - :rtype: str + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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) -class CountryInstance(InstanceResource): - """ """ + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - def __init__(self, version, payload, iso_country=None): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: """ - Initialize the 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. - :returns: twilio.rest.pricing.v2.voice.country.CountryInstance - :rtype: twilio.rest.pricing.v2.voice.country.CountryInstance + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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(CountryInstance, self).__init__(version) - # 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'), - } + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - # Context - self._context = None - self._solution = {'iso_country': iso_country or self._properties['iso_country'], } + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CountryInstance and returns headers from first page - @property - def _proxy(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: ApiResponse with list of instances, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: CountryContext for this CountryInstance - :rtype: twilio.rest.pricing.v2.voice.country.CountryContext + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - if self._context is None: - self._context = CountryContext(self._version, iso_country=self._solution['iso_country'], ) - return self._context + Asynchronously lists CountryInstance and returns headers from first page - @property - def 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: ApiResponse with list of instances, status code, and headers """ - :returns: The name of the country - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['country'] + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately - @property - def iso_country(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 CountryInstance """ - :returns: The ISO country code - :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 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: """ - return self._properties['iso_country'] + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately - @property - def outbound_prefix_prices(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 CountryInstance """ - :returns: The list of OutboundPrefixPriceWithOrigin records - :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 CountryPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['outbound_prefix_prices'] + Retrieve a single page with response metadata - @property - def inbound_call_prices(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: ApiResponse with CountryPage, status code, and headers """ - :returns: The list of InboundCallPrice records - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['inbound_call_prices'] + Asynchronously retrieve a single page with response metadata - @property - def price_unit(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: ApiResponse with CountryPage, status code, and headers """ - :returns: The currency in which prices are measured, in ISO 4127 format (e.g. usd, eur, jpy) - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> CountryPage: """ - return self._properties['price_unit'] + Retrieve a specific page of CountryInstance 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 CountryInstance """ - :returns: The absolute URL of the resource - :rtype: unicode + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CountryPage: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of CountryInstance """ - Fetch the CountryInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) - :returns: The fetched CountryInstance - :rtype: twilio.rest.pricing.v2.voice.country.CountryInstance + def get(self, iso_country: str) -> CountryContext: """ - return self._proxy.fetch() + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..516e6f4cb4 100644 --- a/twilio/rest/pricing/v2/voice/number.py +++ b/twilio/rest/pricing/v2/voice/number.py @@ -1,282 +1,322 @@ -# 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.api_response import ApiResponse 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): - """ """ +from twilio.base.version import Version - def __init__(self, version): - """ - Initialize the NumberList - :param Version version: Version that contains the resource +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.NumberList - :rtype: twilio.rest.pricing.v2.voice.number.NumberList - """ - super(NumberList, self).__init__(version) + self._solution = { + "destination_number": destination_number or self.destination_number, + } - # Path Solution - self._solution = {} + self._context: Optional[NumberContext] = None - def get(self, destination_number): + @property + def _proxy(self) -> "NumberContext": """ - Constructs a NumberContext - - :param destination_number: The destination number for which to fetch pricing information + 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.v2.voice.number.NumberContext - :rtype: twilio.rest.pricing.v2.voice.number.NumberContext + :returns: NumberContext for this NumberInstance """ - return NumberContext(self._version, destination_number=destination_number, ) + if self._context is None: + self._context = NumberContext( + self._version, + destination_number=self._solution["destination_number"], + ) + return self._context - def __call__(self, destination_number): + def fetch( + self, origination_number: Union[str, object] = values.unset + ) -> "NumberInstance": """ - Constructs a NumberContext + Fetch the NumberInstance - :param destination_number: The destination 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: twilio.rest.pricing.v2.voice.number.NumberContext - :rtype: twilio.rest.pricing.v2.voice.number.NumberContext + :returns: The fetched NumberInstance """ - return NumberContext(self._version, destination_number=destination_number, ) + return self._proxy.fetch( + origination_number=origination_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 - """ - return '' + :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, + ) -class NumberPage(Page): - """ """ - - def __init__(self, version, response, solution): + def fetch_with_http_info( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: """ - Initialize the NumberPage + Fetch the NumberInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - super(NumberPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info( + origination_number=origination_number, + ) - def get_instance(self, payload): + async def fetch_with_http_info_async( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: """ - Build an instance of NumberInstance + Asynchronous coroutine to fetch the NumberInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return NumberInstance(self._version, payload, ) + return await self._proxy.fetch_with_http_info_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) -> tuple: """ - Fetch the NumberInstance + Internal helper for fetch operation - :param unicode origination_number: The origination number for which to fetch pricing information + Returns: + tuple: (payload, status_code, headers) + """ - :returns: The fetched NumberInstance - :rtype: twilio.rest.pricing.v2.voice.number.NumberInstance + params = values.of( + { + "OriginationNumber": origination_number, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: """ - data = values.of({'OriginationNumber': origination_number, }) + Fetch the NumberInstance - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + :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 + """ + payload, _, _ = self._fetch(origination_number=origination_number) return NumberInstance( self._version, payload, - destination_number=self._solution['destination_number'], + destination_number=self._solution["destination_number"], ) - def __repr__(self): + def fetch_with_http_info( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: """ - Provide a friendly representation + Fetch the NumberInstance and return response metadata - :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + origination_number=origination_number + ) + instance = NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) -class NumberInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, destination_number=None): + async def _fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> tuple: """ - Initialize the NumberInstance + Internal async helper for fetch operation - :returns: twilio.rest.pricing.v2.voice.number.NumberInstance - :rtype: twilio.rest.pricing.v2.voice.number.NumberInstance + Returns: + tuple: (payload, status_code, headers) """ - 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'), - } + params = values.of( + { + "OriginationNumber": origination_number, + } + ) - # Context - self._context = None - self._solution = { - 'destination_number': destination_number or self._properties['destination_number'], - } + headers = values.of({}) - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + headers["Accept"] = "application/json" - :returns: NumberContext for this NumberInstance - :rtype: twilio.rest.pricing.v2.voice.number.NumberContext - """ - if self._context is None: - self._context = NumberContext( - self._version, - destination_number=self._solution['destination_number'], - ) - return self._context + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - @property - def destination_number(self): - """ - :returns: The destination phone number, in E.164 format - :rtype: unicode + async def fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: """ - return self._properties['destination_number'] + Asynchronous coroutine to fetch the NumberInstance - @property - def origination_number(self): - """ - :returns: The origination phone number, in E.164 format - :rtype: unicode - """ - return self._properties['origination_number'] + :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. - @property - def country(self): - """ - :returns: The name of the country - :rtype: unicode + :returns: The fetched NumberInstance """ - return self._properties['country'] + payload, _, _ = await self._fetch_async(origination_number=origination_number) + return NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) - @property - def iso_country(self): - """ - :returns: The ISO country code - :rtype: unicode + async def fetch_with_http_info_async( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: """ - return self._properties['iso_country'] + Asynchronous coroutine to fetch the NumberInstance and return response metadata - @property - def outbound_call_prices(self): - """ - :returns: The list of OutboundCallPriceWithOrigin records - :rtype: unicode - """ - return self._properties['outbound_call_prices'] + :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. - @property - def inbound_call_price(self): + :returns: ApiResponse with instance, status code, and headers """ - :returns: The InboundCallPrice record - :rtype: unicode + payload, status_code, headers = await self._fetch_async( + origination_number=origination_number + ) + instance = NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - return self._properties['inbound_call_price'] + Provide a friendly representation - @property - def price_unit(self): + :returns: Machine friendly representation """ - :returns: The currency in which prices are measured, in ISO 4127 format (e.g. usd, eur, jpy) - :rtype: unicode + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NumberList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['price_unit'] + Initialize the NumberList + + :param version: Version that contains the resource - @property - def url(self): """ - :returns: The absolute URL of the resource - :rtype: unicode + super().__init__(version) + + def get(self, destination_number: str) -> NumberContext: """ - return self._properties['url'] + Constructs a NumberContext - def fetch(self, origination_number=values.unset): + :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. """ - Fetch the NumberInstance + return NumberContext(self._version, destination_number=destination_number) - :param unicode origination_number: The origination number for which to fetch pricing information + def __call__(self, destination_number: str) -> NumberContext: + """ + 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 227ac038bb..82b845dfb5 100644 --- a/twilio/rest/proxy/v1/service/__init__.py +++ b/twilio/rest/proxy/v1/service/__init__.py @@ -1,610 +1,1476 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page from twilio.rest.proxy.v1.service.phone_number import PhoneNumberList from twilio.rest.proxy.v1.service.session import SessionList -from twilio.rest.proxy.v1.service.short_code import ShortCodeList -class ServiceList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ServiceInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the ServiceList + class GeoMatchLevel(object): + AREA_CODE = "area-code" + OVERLAY = "overlay" + RADIUS = "radius" + COUNTRY = "country" - :param Version version: Version that contains the resource + class NumberSelectionBehavior(object): + AVOID_STICKY = "avoid-sticky" + PREFER_STICKY = "prefer-sticky" - :returns: twilio.rest.proxy.v1.service.ServiceList - :rtype: twilio.rest.proxy.v1.service.ServiceList - """ - super(ServiceList, self).__init__(version) + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. Supports UTF-8 characters. **This value should not have PII.** + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + :ivar callback_url: The URL we call when the interaction status changes. + :ivar default_ttl: The default `ttl` value for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :ivar number_selection_behavior: + :ivar geo_match_level: + :ivar intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :ivar out_of_session_callback_url: The URL we call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar url: The absolute URL of the Service resource. + :ivar links: The URLs of resources related to the Service. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_instance_sid: Optional[str] = payload.get("chat_instance_sid") + self.callback_url: Optional[str] = payload.get("callback_url") + self.default_ttl: Optional[int] = deserialize.integer( + payload.get("default_ttl") + ) + self.number_selection_behavior: Optional[ + "ServiceInstance.NumberSelectionBehavior" + ] = payload.get("number_selection_behavior") + self.geo_match_level: Optional["ServiceInstance.GeoMatchLevel"] = payload.get( + "geo_match_level" + ) + self.intercept_callback_url: Optional[str] = payload.get( + "intercept_callback_url" + ) + self.out_of_session_callback_url: Optional[str] = payload.get( + "out_of_session_callback_url" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") - # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[ServiceContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "ServiceContext": """ - Streams ServiceInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.ServiceInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the ServiceInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists ServiceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the ServiceInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.ServiceInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately + Deletes the ServiceInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with success boolean, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.delete_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info - return ServicePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with success boolean, status code, and headers """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately + return await self._proxy.delete_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance - :returns: Page of ServiceInstance - :rtype: twilio.rest.proxy.v1.service.ServicePage + + :returns: The fetched ServiceInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + - return ServicePage(self._version, response, self._solution) + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() - 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Create the ServiceInstance + Fetch the ServiceInstance with HTTP info - :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 - :returns: The created ServiceInstance - :rtype: twilio.rest.proxy.v1.service.ServiceInstance + :returns: ApiResponse with instance, status code, and headers """ - 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, - }) + return self._proxy.fetch_with_http_info() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info - return ServiceInstance(self._version, payload, ) - def get(self, sid): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a ServiceContext + return await self._proxy.fetch_with_http_info_async() - :param sid: The unique string that identifies the resource + 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 - :returns: twilio.rest.proxy.v1.service.ServiceContext - :rtype: twilio.rest.proxy.v1.service.ServiceContext + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The updated ServiceInstance """ - return ServiceContext(self._version, sid=sid, ) + 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, + ) - def __call__(self, 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 """ - Constructs a ServiceContext + return await self._proxy.update_async( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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, + ) - :param sid: The unique string that identifies the resource + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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: twilio.rest.proxy.v1.service.ServiceContext - :rtype: twilio.rest.proxy.v1.service.ServiceContext + @property + def phone_numbers(self) -> PhoneNumberList: """ - return ServiceContext(self._version, sid=sid, ) + Access the phone_numbers + """ + return self._proxy.phone_numbers + + @property + def sessions(self) -> SessionList: + """ + Access the sessions + """ + return self._proxy.sessions - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ServicePage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ServiceContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the ServicePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the ServiceContext - :returns: twilio.rest.proxy.v1.service.ServicePage - :rtype: twilio.rest.proxy.v1.service.ServicePage + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - super(ServicePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._phone_numbers: Optional[PhoneNumberList] = None + self._sessions: Optional[SessionList] = None - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of ServiceInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :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): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the ServiceInstance and return response metadata -class ServiceContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the ServiceContext - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource + headers = values.of({}) - :returns: twilio.rest.proxy.v1.service.ServiceContext - :rtype: twilio.rest.proxy.v1.service.ServiceContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(ServiceContext, self).__init__(version) + Asynchronous coroutine that deletes the ServiceInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) - # Dependents - self._sessions = None - self._phone_numbers = None - self._short_codes = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", 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, ) + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance and return response metadata - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - def delete(self): + :returns: ApiResponse with instance, status code, and headers """ - Deletes the ServiceInstance + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def _fetch_async(self) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal async helper for fetch operation - 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): + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._update( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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({}) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - @property - def sessions(self): - """ - Access the sessions + return await self._version.update_with_response_info_async( + 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 + 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 + payload, _, _ = await self._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, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 - - :returns: twilio.rest.proxy.v1.service.short_code.ShortCodeList - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeList + Access the sessions """ - if self._short_codes is None: - self._short_codes = ShortCodeList(self._version, service_sid=self._solution['sid'], ) - return self._short_codes + if self._sessions is None: + self._sessions = SessionList( + self._version, + self._solution["sid"], + ) + return self._sessions - def __repr__(self): + def __repr__(self) -> str: """ Provide 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. """ - - class GeoMatchLevel(object): - AREA_CODE = "area-code" - OVERLAY = "overlay" - RADIUS = "radius" - COUNTRY = "country" +class ServicePage(Page): - class NumberSelectionBehavior(object): - AVOID_STICKY = "avoid-sticky" - PREFER_STICKY = "prefer-sticky" + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance - 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'), - } + :param payload: Payload response from the API + """ - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + return ServiceInstance(self._version, payload) - @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: ServiceContext for this ServiceInstance - :rtype: twilio.rest.proxy.v1.service.ServiceContext + :returns: Machine friendly representation """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context + return "" - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + +class ServiceList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['sid'] + Initialize the ServiceList + + :param version: Version that contains the resource - @property - def unique_name(self): """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + super().__init__(version) + + self._uri = "/Services" + + def _create( + self, + unique_name: str, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> tuple: """ - return self._properties['unique_name'] + Internal helper for create operation - @property - def account_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the Account that created the resource - :rtype: unicode + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['account_sid'] + Create the ServiceInstance - @property - def chat_instance_sid(self): + :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 SID of the Chat Service Instance - :rtype: unicode + payload, _, _ = self._create( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + 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, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - return self._properties['chat_instance_sid'] + payload, _, _ = await self._create_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, + ) + return ServiceInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_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, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def callback_url(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: """ - :returns: The URL we call when the interaction status changes - :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 limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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['callback_url'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def default_ttl(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: """ - :returns: Default TTL for a Session, in seconds - :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 limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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_ttl'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def number_selection_behavior(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The preference for Proxy Number selection for the Service instance - :rtype: ServiceInstance.NumberSelectionBehavior + Streams ServiceInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['number_selection_behavior'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def geo_match_level(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: Where a proxy number must be located relative to the participant identifier - :rtype: ServiceInstance.GeoMatchLevel + Asynchronously streams ServiceInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['geo_match_level'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def intercept_callback_url(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: """ - :returns: The URL we call on each interaction - :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 limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to 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['intercept_callback_url'] - @property - def out_of_session_callback_url(self): + return 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]: """ - :returns: The URL we call when an inbound call or SMS action occurs on a closed or non-existent Session - :rtype: unicode + 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 self._properties['out_of_session_callback_url'] - @property - def date_created(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_created'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def date_updated(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_updated'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> ServicePage: """ - :returns: The absolute URL of the Service resource - :rtype: unicode + 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 """ - 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 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: """ - :returns: The URLs of resources related to the Service - :rtype: unicode + 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 """ - 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 ServicePage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Fetch the ServiceInstance + Retrieve a single page with response metadata - :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: ApiResponse with ServicePage, status code, and headers """ - 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 delete(self): + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the ServiceInstance + Asynchronously retrieve a single page with response metadata - :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: ApiResponse with ServicePage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - 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): + 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 + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.proxy.v1.service.session.SessionList - :rtype: twilio.rest.proxy.v1.service.session.SessionList + :returns: Page of ServiceInstance """ - return self._proxy.sessions + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) - @property - def phone_numbers(self): + def get(self, sid: str) -> ServiceContext: """ - Access the phone_numbers + Constructs a ServiceContext - :returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberList - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberList + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - return self._proxy.phone_numbers + return ServiceContext(self._version, sid=sid) - @property - def short_codes(self): + def __call__(self, sid: str) -> ServiceContext: """ - Access the short_codes + Constructs a ServiceContext - :returns: twilio.rest.proxy.v1.service.short_code.ShortCodeList - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeList + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - return self._proxy.short_codes + return ServiceContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/proxy/v1/service/phone_number.py b/twilio/rest/proxy/v1/service/phone_number.py index 022a30b7be..8d206f2e06 100644 --- a/twilio/rest/proxy/v1/service/phone_number.py +++ b/twilio/rest/proxy/v1/service/phone_number.py @@ -1,465 +1,1127 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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, + } - def __init__(self, version, service_sid): + self._context: Optional[PhoneNumberContext] = None + + @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 PhoneNumber resource's parent Service resource + :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.proxy.v1.service.phone_number.PhoneNumberList - :rtype: twilio.rest.proxy.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, sid=values.unset, phone_number=values.unset, - is_reserved=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the PhoneNumberInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance - :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 await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PhoneNumberInstance with HTTP info - return PhoneNumberInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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 self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched PhoneNumberInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "PhoneNumberInstance": """ - Lists PhoneNumberInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine to fetch the PhoneNumberInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance] + :returns: The fetched PhoneNumberInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of PhoneNumberInstance records from the API. - Request is executed immediately + Fetch the PhoneNumberInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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.proxy.v1.service.phone_number.PhoneNumberPage + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info - return PhoneNumberPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of PhoneNumberInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() + + def update( + self, is_reserved: Union[bool, object] = values.unset + ) -> "PhoneNumberInstance": + """ + 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 self._proxy.update( + is_reserved=is_reserved, ) - return PhoneNumberPage(self._version, response, self._solution) + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to update the PhoneNumberInstance + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated PhoneNumberInstance + """ + return await self._proxy.update_async( + is_reserved=is_reserved, + ) - def get(self, sid): + def update_with_http_info( + self, is_reserved: Union[bool, object] = values.unset + ) -> ApiResponse: """ - Constructs a PhoneNumberContext + Update the PhoneNumberInstance with HTTP info - :param sid: The unique string that identifies the resource + :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: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext + :returns: ApiResponse with instance, status code, and headers """ - return PhoneNumberContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + is_reserved=is_reserved, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> ApiResponse: """ - Constructs a PhoneNumberContext + Asynchronous coroutine to update the PhoneNumberInstance with HTTP info - :param sid: The unique string that identifies the resource + :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: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext + :returns: ApiResponse with instance, status code, and headers """ - return PhoneNumberContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + is_reserved=is_reserved, + ) - 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): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class PhoneNumberContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the PhoneNumberPage - - :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 + Initialize the PhoneNumberContext - :returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberPage - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberPage + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the PhoneNumber resource to update. + :param sid: The Twilio-provided string that uniquely identifies the PhoneNumber resource to update. """ - super(PhoneNumberPage, 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}/PhoneNumbers/{sid}".format( + **self._solution + ) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of PhoneNumberInstance - - :param dict payload: Payload response from the API + Internal helper for delete operation - :returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - return PhoneNumberInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - Provide a friendly representation + Deletes the PhoneNumberInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + success, _, _ = self._delete() + return success + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PhoneNumberInstance and return response metadata -class PhoneNumberContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, service_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the PhoneNumberContext + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :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 + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation - :returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext + Returns: + tuple: (success_boolean, status_code, headers) """ - 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({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - def delete(self): + async def delete_async(self) -> bool: """ - Deletes the PhoneNumberInstance + Asynchronous coroutine that deletes the PhoneNumberInstance + :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - def fetch(self): + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PhoneNumberInstance: """ Fetch the PhoneNumberInstance + :returns: The fetched PhoneNumberInstance - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PhoneNumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = await self._fetch_async() 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"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def update(self, is_reserved=values.unset): + def _update(self, is_reserved: Union[bool, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, is_reserved: Union[bool, object] = values.unset + ) -> PhoneNumberInstance: """ 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._update(is_reserved=is_reserved) + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, is_reserved: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Update the PhoneNumberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(is_reserved=is_reserved) + instance = PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> PhoneNumberInstance: + """ + Asynchronous coroutine to update the PhoneNumberInstance - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :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, _, _ = await self._update_async(is_reserved=is_reserved) 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"], + ) + + async def update_with_http_info_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PhoneNumberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + is_reserved=is_reserved + ) + instance = PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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')), +class PhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: + """ + Build an instance of PhoneNumberInstance + + :param payload: Payload response from the API + """ + + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the PhoneNumber resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/PhoneNumbers".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: PhoneNumberContext for this PhoneNumberInstance - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> PhoneNumberInstance: """ - if self._context is None: - self._context = PhoneNumberContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the PhoneNumberInstance - @property - def sid(self): + :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. + :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The created PhoneNumberInstance """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = self._create( + sid=sid, phone_number=phone_number, is_reserved=is_reserved + ) + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['sid'] + Create the PhoneNumberInstance and return response metadata - @property - def account_sid(self): + :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. + :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Account that created the resource - :rtype: unicode + payload, status_code, headers = self._create( + sid=sid, phone_number=phone_number, is_reserved=is_reserved + ) + instance = PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for create operation - @property - def service_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the PhoneNumber resource's parent Service resource - :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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> PhoneNumberInstance: """ - return self._properties['service_sid'] + Asynchronously create the PhoneNumberInstance - @property - def date_created(self): + :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. + :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The created PhoneNumberInstance """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + payload, _, _ = await self._create_async( + sid=sid, phone_number=phone_number, is_reserved=is_reserved + ) + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_created'] + Asynchronously create the PhoneNumberInstance and return response metadata - @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: ApiResponse with instance, status code, and headers """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + payload, status_code, headers = await self._create_async( + sid=sid, phone_number=phone_number, is_reserved=is_reserved + ) + instance = PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PhoneNumberInstance]: """ - return self._properties['date_updated'] + Streams PhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - @property - def phone_number(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The phone number in E.164 format - :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['phone_number'] + 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['friendly_name'] + Streams PhoneNumberInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The ISO Country Code - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['iso_country'] + Asynchronously streams PhoneNumberInstance and returns headers from first page - @property - def capabilities(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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: """ - :returns: The capabilities of the phone number - :rtype: unicode + 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['capabilities'] - @property - def url(self): + return 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]: """ - :returns: The absolute URL of the PhoneNumber resource - :rtype: unicode + 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['url'] - @property - def is_reserved(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: Reserve the phone number for manual assignment to participants only - :rtype: bool + Lists PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['is_reserved'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def in_use(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The number of open session assigned to the number. - :rtype: unicode + Asynchronously lists PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['in_use'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - 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, + ) -> PhoneNumberPage: """ - Deletes the PhoneNumberInstance + Retrieve a single page of PhoneNumberInstance 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 PhoneNumberInstance """ - 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 fetch(self): + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, solution=self._solution) + + async def 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: """ - Fetch the PhoneNumberInstance + Asynchronously retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately - :returns: The fetched PhoneNumberInstance - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance + :param page_token: PageToken provided by the API + :param page_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._proxy.fetch() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - def update(self, is_reserved=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 PhoneNumberPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Update the PhoneNumberInstance + Retrieve a single page with response metadata - :param bool is_reserved: Whether the new phone number should be reserved - :returns: The updated PhoneNumberInstance - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PhoneNumberPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PhoneNumberPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> PhoneNumberPage: + """ + Retrieve a specific page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PhoneNumberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PhoneNumberPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> PhoneNumberPage: + """ + Asynchronously retrieve a specific page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PhoneNumberInstance """ - return self._proxy.update(is_reserved=is_reserved, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return PhoneNumberPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param sid: The Twilio-provided string that uniquely identifies the PhoneNumber resource to update. + """ + return PhoneNumberContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param sid: The Twilio-provided string that uniquely identifies the PhoneNumber resource to update. + """ + return PhoneNumberContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 d4f248539b..ba7ee376b3 100644 --- a/twilio/rest/proxy/v1/service/session/__init__.py +++ b/twilio/rest/proxy/v1/service/session/__init__.py @@ -1,593 +1,1323 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): + + class Mode(object): + MESSAGE_ONLY = "message-only" + VOICE_ONLY = "voice-only" + VOICE_AND_MESSAGE = "voice-and-message" + + class Status(object): + OPEN = "open" + IN_PROGRESS = "in-progress" + CLOSED = "closed" + FAILED = "failed" + UNKNOWN = "unknown" + + """ + :ivar sid: The unique string that we created to identify the Session resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/proxy/api/service) the session is associated with. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Session resource. + :ivar date_started: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session started. + :ivar date_ended: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session ended. + :ivar date_last_interaction: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session last had an interaction. + :ivar date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :ivar unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. Supports UTF-8 characters. **This value should not have PII.** + :ivar status: + :ivar closed_reason: The reason the Session ended. + :ivar ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :ivar mode: + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar url: The absolute URL of the Session resource. + :ivar links: The URLs of resources related to the Session. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_started: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_started") + ) + self.date_ended: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_ended") + ) + self.date_last_interaction: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_last_interaction") + ) + self.date_expiry: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expiry") + ) + self.unique_name: Optional[str] = payload.get("unique_name") + self.status: Optional["SessionInstance.Status"] = payload.get("status") + self.closed_reason: Optional[str] = payload.get("closed_reason") + self.ttl: Optional[int] = deserialize.integer(payload.get("ttl")) + self.mode: Optional["SessionInstance.Mode"] = payload.get("mode") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[SessionContext] = None - def __init__(self, version, service_sid): + @property + def _proxy(self) -> "SessionContext": """ - Initialize the SessionList + 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 + :returns: SessionContext for this SessionInstance + """ + if self._context is None: + self._context = SessionContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.proxy.v1.service.session.SessionList - :rtype: twilio.rest.proxy.v1.service.session.SessionList + def delete(self) -> bool: """ - super(SessionList, self).__init__(version) + Deletes the SessionInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Sessions'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: """ - 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. + Asynchronous coroutine that deletes the SessionInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SessionInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists SessionInstance 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.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SessionInstance with HTTP info - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "SessionInstance": """ - Retrieve a single page of SessionInstance records from the API. - Request is executed immediately + Fetch the SessionInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionPage + :returns: The fetched SessionInstance """ - 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) -> "SessionInstance": + """ + Asynchronous coroutine to 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 + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SessionInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionPage + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SessionInstance with HTTP info - 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: ApiResponse with instance, status code, and headers """ - Create the SessionInstance + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> "SessionInstance": + """ + Update the SessionInstance - :param 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 + :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 created SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionInstance + :returns: The updated SessionInstance """ - data = values.of({ - 'UniqueName': unique_name, - 'DateExpiry': serialize.iso8601_datetime(date_expiry), - 'Ttl': ttl, - 'Mode': mode, - 'Status': status, - 'Participants': serialize.map(participants, lambda e: serialize.object(e)), - }) + return self._proxy.update( + date_expiry=date_expiry, + ttl=ttl, + status=status, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def update_async( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> "SessionInstance": + """ + Asynchronous coroutine to update the SessionInstance - return SessionInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: - def get(self, sid): + :returns: The updated SessionInstance """ - Constructs a SessionContext + return await self._proxy.update_async( + date_expiry=date_expiry, + ttl=ttl, + status=status, + ) + + def update_with_http_info( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Update the SessionInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return SessionContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + date_expiry=date_expiry, + ttl=ttl, + status=status, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> ApiResponse: """ - Constructs a SessionContext + Asynchronous coroutine to update the SessionInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + date_expiry=date_expiry, + ttl=ttl, + status=status, + ) - :param sid: The unique string that identifies the resource + @property + def interactions(self) -> InteractionList: + """ + Access the interactions + """ + return self._proxy.interactions - :returns: twilio.rest.proxy.v1.service.session.SessionContext - :rtype: twilio.rest.proxy.v1.service.session.SessionContext + @property + def participants(self) -> ParticipantList: """ - return SessionContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Access the participants + """ + return self._proxy.participants - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SessionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SessionContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the SessionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: 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) -> tuple: """ - Build an instance of SessionInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.proxy.v1.service.session.SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionInstance + def delete(self) -> bool: """ - return SessionInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the SessionInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the SessionInstance and return response metadata -class SessionContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the SessionContext - :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 + headers = values.of({}) - :returns: twilio.rest.proxy.v1.service.session.SessionContext - :rtype: twilio.rest.proxy.v1.service.session.SessionContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(SessionContext, self).__init__(version) + Asynchronous coroutine that deletes the SessionInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SessionInstance and return response metadata - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Sessions/{sid}'.format(**self._solution) - # Dependents - self._interactions = None - self._participants = None + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - def fetch(self): + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SessionInstance: """ Fetch the SessionInstance + :returns: The fetched SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SessionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SessionInstance: + """ + Asynchronous coroutine to fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the SessionInstance + Asynchronous coroutine to fetch the SessionInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for update operation - def update(self, date_expiry=values.unset, ttl=values.unset, - status=values.unset): + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> SessionInstance: """ Update the SessionInstance - :param 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._update(date_expiry=date_expiry, ttl=ttl, status=status) + return SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def update_with_http_info( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Update the SessionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + date_expiry=date_expiry, ttl=ttl, status=status + ) + instance = SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> SessionInstance: + """ + Asynchronous coroutine to update the SessionInstance + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: The updated SessionInstance + """ + payload, _, _ = await self._update_async( + date_expiry=date_expiry, ttl=ttl, status=status + ) return SessionInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SessionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + date_expiry=date_expiry, ttl=ttl, status=status + ) + instance = SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @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) + 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" +class SessionPage(Page): - class Mode(object): - MESSAGE_ONLY = "message-only" - VOICE_ONLY = "voice-only" - VOICE_AND_MESSAGE = "voice-and-message" + def get_instance(self, payload: Dict[str, Any]) -> SessionInstance: + """ + Build an instance of SessionInstance - 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'), - } + :param payload: Payload response from the API + """ - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + return SessionInstance( + 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: SessionContext for this SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionContext + :returns: Machine friendly representation """ - if self._context is None: - self._context = SessionContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return "" - @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 resource's parent Service - :rtype: unicode - """ - return self._properties['service_sid'] +class SessionList(ListResource): - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def __init__(self, version: Version, service_sid: str): """ - return self._properties['account_sid'] + Initialize the SessionList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to read. - @property - def date_started(self): """ - :returns: The ISO 8601 date when the Session started - :rtype: datetime + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Sessions".format(**self._solution) + + def _create( + self, + unique_name: Union[str, object] = values.unset, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + mode: Union["SessionInstance.Mode", object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + participants: Union[List[object], object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['date_started'] + Create the SessionInstance - @property - def date_ended(self): + :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 """ - :returns: The ISO 8601 date when the Session ended - :rtype: datetime + payload, _, _ = self._create( + unique_name=unique_name, + date_expiry=date_expiry, + ttl=ttl, + mode=mode, + status=status, + participants=participants, + ) + return SessionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the SessionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + date_expiry=date_expiry, + ttl=ttl, + mode=mode, + status=status, + participants=participants, + ) + instance = SessionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['date_ended'] + payload, _, _ = await self._create_async( + unique_name=unique_name, + date_expiry=date_expiry, + ttl=ttl, + mode=mode, + status=status, + participants=participants, + ) + return SessionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def date_last_interaction(self): + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the SessionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + date_expiry=date_expiry, + ttl=ttl, + mode=mode, + status=status, + participants=participants, + ) + instance = SessionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SessionInstance]: """ - :returns: The ISO 8601 date when the Session last had an interaction - :rtype: datetime + 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_last_interaction'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def date_expiry(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 when the Session should expire - :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_expiry'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def unique_name(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + Streams SessionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['unique_name'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def status(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The status of the Session - :rtype: SessionInstance.Status + Asynchronously streams SessionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['status'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def closed_reason(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SessionInstance]: """ - :returns: The reason the Session ended - :rtype: unicode + 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['closed_reason'] - @property - def ttl(self): + return 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]: """ - :returns: When the session will expire - :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['ttl'] - @property - def mode(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The Mode of the Session - :rtype: SessionInstance.Mode + Lists SessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['mode'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def date_created(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Asynchronously lists SessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_created'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> SessionPage: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + 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['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 SessionPage(self._version, response, solution=self._solution) + + async def 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: """ - :returns: The absolute URL of the Session resource - :rtype: unicode + 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 """ - 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 SessionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The URLs of resources related to the Session - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SessionPage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SessionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Fetch the SessionInstance + Asynchronously retrieve a single page with response metadata - :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: ApiResponse with SessionPage, status code, and headers """ - 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 delete(self): + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SessionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 cb4a34b76e..abf834776c 100644 --- a/twilio/rest/proxy/v1/service/session/interaction.py +++ b/twilio/rest/proxy/v1/service/session/interaction.py @@ -1,531 +1,876 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists 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 delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of InteractionInstance records from the API. - Request is executed immediately + Deletes the InteractionInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with success boolean, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.delete_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InteractionInstance with HTTP info - return InteractionPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with success boolean, status code, and headers """ - Retrieve a specific page of InteractionInstance records from the API. - Request is executed immediately + return await self._proxy.delete_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def fetch(self) -> "InteractionInstance": + """ + Fetch the InteractionInstance - :returns: Page of InteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionPage + + :returns: The fetched InteractionInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch() + + async def fetch_async(self) -> "InteractionInstance": + """ + Asynchronous coroutine to fetch the InteractionInstance - return InteractionPage(self._version, response, self._solution) - def get(self, sid): + :returns: The fetched InteractionInstance """ - Constructs a InteractionContext + return await self._proxy.fetch_async() - :param sid: The unique string that identifies the resource + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionInstance with HTTP info - :returns: twilio.rest.proxy.v1.service.session.interaction.InteractionContext - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionContext + + :returns: ApiResponse with instance, status code, and headers """ - return InteractionContext( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - sid=sid, - ) + return self._proxy.fetch_with_http_info() - def __call__(self, sid): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Constructs a InteractionContext + Asynchronous coroutine to fetch the InteractionInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return InteractionContext( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - sid=sid, - ) + return await self._proxy.fetch_with_http_info_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 InteractionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class InteractionContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, session_sid: str, sid: str): """ - Initialize the InteractionPage - - :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 + Initialize the InteractionContext - :returns: twilio.rest.proxy.v1.service.session.interaction.InteractionPage - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionPage + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to fetch. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Interaction resource to fetch. """ - super(InteractionPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of InteractionInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.proxy.v1.service.session.interaction.InteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionInstance + def delete(self) -> bool: """ - return InteractionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], + Deletes the InteractionInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InteractionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + 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 '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InteractionInstance and return response metadata -class InteractionContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, service_sid, session_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the InteractionContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, 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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.proxy.v1.service.session.interaction.InteractionContext - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionContext + Returns: + tuple: (payload, status_code, headers) """ - 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) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> InteractionInstance: """ Fetch the InteractionInstance + :returns: The fetched InteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - + payload, _, _ = self._fetch() 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"], + sid=self._solution["sid"], ) - def delete(self): + def fetch_with_http_info(self) -> ApiResponse: """ - Deletes the InteractionInstance + Fetch the InteractionInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def __repr__(self): + :returns: ApiResponse with instance, status code, and headers """ - Provide a friendly representation + payload, status_code, headers = self._fetch() + instance = InteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: Machine friendly representation - :rtype: str + async def _fetch_async(self) -> tuple: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Internal async helper for fetch operation + Returns: + tuple: (payload, status_code, headers) + """ -class InteractionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers = values.of({}) - class Type(object): - MESSAGE = "message" - VOICE = "voice" - UNKNOWN = "unknown" + headers["Accept"] = "application/json" - 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" + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - 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'), - } + async def fetch_async(self) -> InteractionInstance: + """ + Asynchronous coroutine to fetch the InteractionInstance - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'session_sid': session_sid, - 'sid': sid or self._properties['sid'], - } - @property - def _proxy(self): + :returns: The fetched InteractionInstance """ - 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._fetch_async() + return InteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) - :returns: InteractionContext for this InteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionContext + async def fetch_with_http_info_async(self) -> ApiResponse: """ - 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 + Asynchronous coroutine to fetch the InteractionInstance and return response metadata - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['sid'] + payload, status_code, headers = await self._fetch_async() + instance = InteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def session_sid(self): + def __repr__(self) -> str: """ - :returns: The SID of the resource's parent Session - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['session_sid'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def service_sid(self): + +class InteractionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InteractionInstance: """ - :returns: The SID of the resource's parent Service - :rtype: unicode + Build an instance of InteractionInstance + + :param payload: Payload response from the API """ - return self._properties['service_sid'] - @property - def account_sid(self): + return InteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + + def __repr__(self) -> str: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def data(self): + +class InteractionList(ListResource): + + def __init__(self, version: Version, service_sid: str, session_sid: str): """ - :returns: A JSON string that includes the message body of message interactions - :rtype: unicode + Initialize the InteractionList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) to read the resources from. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) to read the resources from. + """ - return self._properties['data'] + super().__init__(version) - @property - def type(self): + # Path Solution + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + } + self._uri = ( + "/Services/{service_sid}/Sessions/{session_sid}/Interactions".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InteractionInstance]: """ - :returns: The Type of the Interaction - :rtype: InteractionInstance.Type + Streams InteractionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['type'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def inbound_participant_sid(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InteractionInstance]: """ - :returns: The SID of the inbound Participant resource - :rtype: unicode + Asynchronously streams InteractionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['inbound_participant_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def inbound_resource_sid(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the inbound resource - :rtype: unicode + Streams InteractionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['inbound_resource_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def inbound_resource_status(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The inbound resource status of the Interaction - :rtype: InteractionInstance.ResourceStatus + Asynchronously streams InteractionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['inbound_resource_status'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def inbound_resource_type(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionInstance]: """ - :returns: The inbound resource type - :rtype: unicode + Lists InteractionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['inbound_resource_type'] - @property - def inbound_resource_url(self): + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionInstance]: """ - :returns: The URL of the Twilio inbound resource - :rtype: unicode + Asynchronously lists InteractionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['inbound_resource_url'] - @property - def outbound_participant_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the outbound Participant - :rtype: unicode + Lists InteractionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['outbound_participant_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def outbound_resource_sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the outbound resource - :rtype: unicode + Asynchronously lists InteractionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['outbound_resource_sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def outbound_resource_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, + ) -> InteractionPage: """ - :returns: The outbound resource status of the Interaction - :rtype: InteractionInstance.ResourceStatus + 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['outbound_resource_status'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def outbound_resource_type(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 InteractionPage(self._version, response, solution=self._solution) + + async def 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 outbound resource type - :rtype: unicode + 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['outbound_resource_type'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def outbound_resource_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 InteractionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The URL of the Twilio outbound resource - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionPage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InteractionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The ISO 8601 date and time in GMT when the Interaction was created - :rtype: datetime + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InteractionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 9e57541728..90c3af7080 100644 --- a/twilio/rest/proxy/v1/service/session/participant/__init__.py +++ b/twilio/rest/proxy/v1/service/session/participant/__init__.py @@ -1,509 +1,1039 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -from twilio.rest.proxy.v1.service.session.participant.message_interaction import MessageInteractionList +from twilio.rest.proxy.v1.service.session.participant.message_interaction import ( + MessageInteractionList, +) -class ParticipantList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ParticipantInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Participant resource. + :ivar session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) resource. + :ivar service_sid: The SID of the resource's parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Participant resource. + :ivar friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. Supports UTF-8 characters. **This value should not have PII.** + :ivar identifier: The phone number or channel identifier of the Participant. This value must be 191 characters or fewer. Supports UTF-8 characters. + :ivar proxy_identifier: The phone number or short code (masked number) of the participant's partner. The participant will call or message the partner participant at this number. + :ivar proxy_identifier_sid: The SID of the Proxy Identifier assigned to the Participant. + :ivar date_deleted: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Participant was removed from the session. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar url: The absolute URL of the Participant resource. + :ivar links: The URLs to resources related the participant. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + session_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.session_sid: Optional[str] = payload.get("session_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.identifier: Optional[str] = payload.get("identifier") + self.proxy_identifier: Optional[str] = payload.get("proxy_identifier") + self.proxy_identifier_sid: Optional[str] = payload.get("proxy_identifier_sid") + self.date_deleted: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_deleted") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "sid": sid or self.sid, + } + + self._context: Optional[ParticipantContext] = None - def __init__(self, version, service_sid, session_sid): + @property + def _proxy(self) -> "ParticipantContext": """ - Initialize the ParticipantList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: 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. + 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 ParticipantInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.session.participant.ParticipantInstance] + + :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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ParticipantInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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 self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.session.participant.ParticipantInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "ParticipantInstance": """ - Retrieve a single page of ParticipantInstance records from the API. - Request is executed immediately + 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 self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance - return ParticipantPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched ParticipantInstance """ - Retrieve a specific page of ParticipantInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info - return ParticipantPage(self._version, response, self._solution) - def create(self, identifier, friendly_name=values.unset, - proxy_identifier=values.unset, proxy_identifier_sid=values.unset): + :returns: ApiResponse with instance, status code, and headers """ - Create the ParticipantInstance + return await self._proxy.fetch_with_http_info_async() - :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 + @property + def message_interactions(self) -> MessageInteractionList: + """ + Access the message_interactions + """ + return self._proxy.message_interactions - :returns: The created ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance + def __repr__(self) -> str: """ - data = values.of({ - 'Identifier': identifier, - 'FriendlyName': friendly_name, - 'ProxyIdentifier': proxy_identifier, - 'ProxyIdentifierSid': proxy_identifier_sid, - }) + Provide a friendly representation - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - return ParticipantInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - ) - def get(self, sid): +class ParticipantContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, session_sid: str, sid: str): """ - Constructs a ParticipantContext + Initialize the ParticipantContext - :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 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) - :returns: twilio.rest.proxy.v1.service.session.participant.ParticipantContext - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantContext + # Path Solution + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Sessions/{session_sid}/Participants/{sid}".format( + **self._solution + ) + ) + + self._message_interactions: Optional[MessageInteractionList] = None + + def _delete(self) -> tuple: """ - return ParticipantContext( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - sid=sid, + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers ) - def __call__(self, sid): + def delete(self) -> bool: """ - Constructs a ParticipantContext + 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, + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ParticipantInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the ParticipantInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance and return response metadata -class ParticipantPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, response, solution): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the ParticipantPage + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :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 _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.proxy.v1.service.session.participant.ParticipantPage - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantPage + Returns: + tuple: (payload, status_code, headers) """ - super(ParticipantPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", 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.proxy.v1.service.session.participant.ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance + :returns: The fetched ParticipantInstance """ + payload, _, _ = self._fetch() 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"], + sid=self._solution["sid"], ) - def __repr__(self): + def fetch_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - + Fetch the ParticipantInstance and return response metadata -class ParticipantContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, service_sid, session_sid, sid): + :returns: ApiResponse with instance, status code, and headers """ - Initialize the ParticipantContext + payload, status_code, headers = self._fetch() + instance = ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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: The SID of the parent Session of the resource to fetch - :param sid: The unique string that identifies the resource + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: twilio.rest.proxy.v1.service.session.participant.ParticipantContext - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantContext + Returns: + tuple: (payload, status_code, headers) """ - super(ParticipantContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'session_sid': session_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Sessions/{session_sid}/Participants/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._message_interactions = None + headers["Accept"] = "application/json" - def fetch(self): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ParticipantInstance: """ - Fetch the ParticipantInstance + Asynchronous coroutine to fetch the ParticipantInstance + :returns: The fetched ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - + payload, _, _ = await self._fetch_async() 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"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the ParticipantInstance + Asynchronous coroutine to fetch the ParticipantInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def message_interactions(self): + def message_interactions(self) -> MessageInteractionList: """ 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 """ 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'], + self._solution["service_sid"], + self._solution["session_sid"], + self._solution["sid"], ) return self._message_interactions - def __repr__(self): + def __repr__(self) -> str: """ Provide 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. """ - - 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'), - } +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation - # Context - self._context = None + :returns: Machine friendly representation + """ + return "" + + +class ParticipantList(ListResource): + + def __init__(self, version: Version, service_sid: str, session_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resources to read. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resources to read. + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'session_sid': session_sid, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "session_sid": session_sid, } + self._uri = ( + "/Services/{service_sid}/Sessions/{session_sid}/Participants".format( + **self._solution + ) + ) - @property - def _proxy(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, + ) -> tuple: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Internal helper for create operation - :returns: ParticipantContext for this ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantContext + Returns: + tuple: (payload, status_code, headers) """ - if self._context is None: - self._context = ParticipantContext( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - sid=self._solution['sid'], - ) - return self._context - @property - def sid(self): + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Create the ParticipantInstance + + :param identifier: The phone number of the Participant. + :param friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. **This value should not have PII.** + :param proxy_identifier: The proxy phone number to use for the Participant. If not specified, Proxy will select a number from the pool. + :param proxy_identifier_sid: The SID of the Proxy Identifier to assign to the Participant. + + :returns: The created ParticipantInstance """ - return self._properties['sid'] + payload, _, _ = self._create( + identifier=identifier, + friendly_name=friendly_name, + proxy_identifier=proxy_identifier, + proxy_identifier_sid=proxy_identifier_sid, + ) + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) - @property - def session_sid(self): + def create_with_http_info( + 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, + ) -> ApiResponse: """ - :returns: The SID of the resource's parent Session - :rtype: unicode + Create the ParticipantInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['session_sid'] + payload, status_code, headers = self._create( + identifier=identifier, + friendly_name=friendly_name, + proxy_identifier=proxy_identifier, + proxy_identifier_sid=proxy_identifier_sid, + ) + instance = ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def service_sid(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, + ) -> tuple: """ - :returns: The SID of the resource's parent Service - :rtype: unicode + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['service_sid'] - @property - def account_sid(self): + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Asynchronously create the ParticipantInstance + + :param identifier: The phone number of the Participant. + :param friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. **This value should not have PII.** + :param proxy_identifier: The proxy phone number to use for the Participant. If not specified, Proxy will select a number from the pool. + :param proxy_identifier_sid: The SID of the Proxy Identifier to assign to the Participant. + + :returns: The created ParticipantInstance """ - return self._properties['account_sid'] + payload, _, _ = await self._create_async( + identifier=identifier, + friendly_name=friendly_name, + proxy_identifier=proxy_identifier, + proxy_identifier_sid=proxy_identifier_sid, + ) + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) - @property - def friendly_name(self): + async def create_with_http_info_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, + ) -> ApiResponse: """ - :returns: The string that you assigned to describe the participant - :rtype: unicode + Asynchronously create the ParticipantInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['friendly_name'] + payload, status_code, headers = await self._create_async( + identifier=identifier, + friendly_name=friendly_name, + proxy_identifier=proxy_identifier, + proxy_identifier_sid=proxy_identifier_sid, + ) + instance = ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def identifier(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: """ - :returns: The phone number of the Participant - :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['identifier'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def proxy_identifier(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: The phone number or short code of the participant's partner - :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['proxy_identifier'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def proxy_identifier_sid(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Proxy Identifier assigned to the Participant - :rtype: unicode + Streams ParticipantInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['proxy_identifier_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def date_deleted(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The ISO 8601 date the Participant was removed - :rtype: datetime + Asynchronously streams ParticipantInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_deleted'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def date_created(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + 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['date_created'] - @property - def date_updated(self): + return 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]: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + 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['date_updated'] - @property - def url(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The absolute URL of the Participant resource - :rtype: unicode + Lists ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['url'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def links(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The URLs to resources related the participant - :rtype: unicode + Asynchronously lists ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['links'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - 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, + ) -> ParticipantPage: """ - Fetch the ParticipantInstance + Retrieve a single 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 page_token: PageToken provided by the API + :param page_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._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 ParticipantPage(self._version, response, solution=self._solution) + + async def 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: """ - Deletes the ParticipantInstance + Asynchronously retrieve a single page of ParticipantInstance 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 ParticipantInstance """ - return self._proxy.delete() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def message_interactions(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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Access the message_interactions + Retrieve a single page with response metadata - :returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers """ - return self._proxy.message_interactions + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: The Twilio-provided string that uniquely identifies the Participant resource to fetch. + """ + return ParticipantContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: The Twilio-provided string that uniquely identifies the Participant resource to fetch. + """ + return ParticipantContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 a04ec33770..49a2c998c4 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,941 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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) - def create(self, body=values.unset, media_url=values.unset): + self._context: Optional[MessageInteractionContext] = None + + @property + def _proxy(self) -> "MessageInteractionContext": """ - Create the MessageInteractionInstance + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param unicode body: Message body - :param unicode media_url: Reserved + :returns: MessageInteractionContext for this MessageInteractionInstance + """ + if self._context is None: + self._context = MessageInteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: The created MessageInteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance + def fetch(self) -> "MessageInteractionInstance": """ - data = values.of({'Body': body, 'MediaUrl': serialize.map(media_url, lambda e: e), }) + Fetch the MessageInteractionInstance - payload = self._version.create(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'], - ) + :returns: The fetched MessageInteractionInstance + """ + return self._proxy.fetch() - def stream(self, limit=None, page_size=None): + async def fetch_async(self) -> "MessageInteractionInstance": """ - Streams MessageInteractionInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Asynchronous coroutine to fetch the MessageInteractionInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance] + :returns: The fetched MessageInteractionInstance """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.fetch_async() - page = self.page(page_size=limits['page_size'], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInteractionInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with instance, status code, and headers """ - 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 self._proxy.fetch_with_http_info() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance] + async def fetch_with_http_info_async(self) -> ApiResponse: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Asynchronous coroutine to fetch the MessageInteractionInstance with HTTP info - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a single page of MessageInteractionInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str page_token: PageToken provided by the API - :param 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 MessageInteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionPage + :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 MessageInteractionPage(self._version, response, self._solution) +class MessageInteractionContext(InstanceContext): - def get_page(self, target_url): + def __init__( + self, + version: Version, + service_sid: str, + session_sid: str, + participant_sid: str, + sid: str, + ): """ - Retrieve a specific page of MessageInteractionInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + Initialize the MessageInteractionContext - :returns: Page of MessageInteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionPage + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to fetch. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resource to fetch. + :param participant_sid: The SID of the [Participant](https://www.twilio.com/docs/proxy/api/participant) resource. + :param sid: The Twilio-provided string that uniquely identifies the MessageInteraction resource to fetch. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "participant_sid": participant_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Sessions/{session_sid}/Participants/{participant_sid}/MessageInteractions/{sid}".format( + **self._solution ) - return MessageInteractionPage(self._version, response, self._solution) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - def get(self, sid): + Returns: + tuple: (payload, status_code, headers) """ - Constructs a MessageInteractionContext - :param sid: The unique string that identifies the resource + headers = values.of({}) + + headers["Accept"] = "application/json" - :returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionContext - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionContext + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInteractionInstance: """ - return MessageInteractionContext( + Fetch the MessageInteractionInstance + + + :returns: The fetched MessageInteractionInstance + """ + payload, _, _ = self._fetch() + 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a MessageInteractionContext + Fetch the MessageInteractionInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return MessageInteractionContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class MessageInteractionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + async def fetch_async(self) -> MessageInteractionInstance: """ - Initialize the MessageInteractionPage + Asynchronous coroutine to fetch the MessageInteractionInstance - :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 + :returns: The fetched MessageInteractionInstance """ - super(MessageInteractionPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = await self._fetch_async() + return MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of MessageInteractionInstance + Asynchronous coroutine to fetch the MessageInteractionInstance and return response metadata - :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 + :returns: ApiResponse with instance, status code, and headers """ - return MessageInteractionInstance( + payload, status_code, headers = await self._fetch_async() + instance = 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"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class MessageInteractionContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, service_sid, session_sid, participant_sid, sid): """ - Initialize the MessageInteractionContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :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 - :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) - - # 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) +class MessageInteractionPage(Page): - def fetch(self): + def get_instance(self, payload: Dict[str, Any]) -> MessageInteractionInstance: """ - Fetch the MessageInteractionInstance + Build an instance of MessageInteractionInstance - :returns: The fetched MessageInteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance + :param payload: Payload response from the API """ - payload = self._version.fetch(method='GET', uri=self._uri, ) 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): + def __repr__(self) -> str: """ Provide a 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 MessageInteractionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class MessageInteractionList(ListResource): - class Type(object): - MESSAGE = "message" - VOICE = "voice" - UNKNOWN = "unknown" + def __init__( + self, version: Version, service_sid: str, session_sid: str, participant_sid: str + ): + """ + 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 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. - 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'), - } + """ + super().__init__(version) - # Context - self._context = None + # Path Solution self._solution = { - 'service_sid': service_sid, - 'session_sid': session_sid, - 'participant_sid': participant_sid, - 'sid': sid or self._properties['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".format( + **self._solution + ) - @property - def _proxy(self): + def _create( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> tuple: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Internal helper for create operation - :returns: MessageInteractionContext for this MessageInteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionContext + Returns: + tuple: (payload, status_code, headers) """ - if self._context is None: - self._context = MessageInteractionContext( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - participant_sid=self._solution['participant_sid'], - sid=self._solution['sid'], - ) - return self._context - @property - def sid(self): + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> MessageInteractionInstance: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Create the MessageInteractionInstance + + :param body: The message to send to the participant + :param media_url: Reserved. Not currently supported. + + :returns: The created MessageInteractionInstance """ - return self._properties['sid'] + payload, _, _ = self._create(body=body, media_url=media_url) + 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 session_sid(self): + def create_with_http_info( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> ApiResponse: """ - :returns: The SID of the resource's parent Session - :rtype: unicode + Create the MessageInteractionInstance and return response metadata + + :param body: The message to send to the participant + :param media_url: Reserved. Not currently supported. + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['session_sid'] + payload, status_code, headers = self._create(body=body, media_url=media_url) + instance = MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def service_sid(self): + async def _create_async( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> tuple: """ - :returns: The SID of the resource's parent Service - :rtype: unicode + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['service_sid'] - @property - def account_sid(self): + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> MessageInteractionInstance: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Asynchronously create the MessageInteractionInstance + + :param body: The message to send to the participant + :param media_url: Reserved. Not currently supported. + + :returns: The created MessageInteractionInstance """ - return self._properties['account_sid'] + payload, _, _ = await self._create_async(body=body, media_url=media_url) + 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 data(self): + async def create_with_http_info_async( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> ApiResponse: """ - :returns: A JSON string that includes the message body sent to the participant - :rtype: unicode + Asynchronously create the MessageInteractionInstance and return response metadata + + :param body: The message to send to the participant + :param media_url: Reserved. Not currently supported. + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['data'] + payload, status_code, headers = await self._create_async( + body=body, media_url=media_url + ) + instance = MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def type(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInteractionInstance]: """ - :returns: The Type of Message Interaction - :rtype: MessageInteractionInstance.Type + Streams MessageInteractionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['type'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def participant_sid(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInteractionInstance]: """ - :returns: The SID of the Participant resource - :rtype: unicode + Asynchronously streams MessageInteractionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['participant_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def inbound_participant_sid(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: Always empty for Message Interactions - :rtype: unicode + Streams MessageInteractionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['inbound_participant_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def inbound_resource_sid(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: Always empty for Message Interactions - :rtype: unicode + Asynchronously streams MessageInteractionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['inbound_resource_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def inbound_resource_status(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInteractionInstance]: """ - :returns: Always empty for Message Interactions - :rtype: MessageInteractionInstance.ResourceStatus + Lists MessageInteractionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['inbound_resource_status'] - @property - def inbound_resource_type(self): + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInteractionInstance]: """ - :returns: Always empty for Message Interactions - :rtype: unicode + Asynchronously lists MessageInteractionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['inbound_resource_type'] - @property - def inbound_resource_url(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: Always empty for Message Interactions - :rtype: unicode + Lists MessageInteractionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['inbound_resource_url'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def outbound_participant_sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the outbound Participant resource - :rtype: unicode + Asynchronously lists MessageInteractionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['outbound_participant_sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> MessageInteractionPage: """ - :returns: The SID of the outbound Message resource - :rtype: unicode + 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_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def outbound_resource_status(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 MessageInteractionPage(self._version, response, solution=self._solution) + + async def 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 outbound resource status - :rtype: MessageInteractionInstance.ResourceStatus + 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_status'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def outbound_resource_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 MessageInteractionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The outbound resource type - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessageInteractionPage, status code, and headers """ - return self._properties['outbound_resource_type'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def outbound_resource_url(self): + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessageInteractionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The URL of the Twilio message resource - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessageInteractionPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessageInteractionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 deleted file mode 100644 index 8dff5acaf7..0000000000 --- a/twilio/rest/proxy/v1/service/short_code.py +++ /dev/null @@ -1,444 +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 ShortCodeList(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 ShortCodeList - - :param Version version: Version that contains the resource - :param service_sid: The SID of the resource's parent Service - - :returns: twilio.rest.proxy.v1.service.short_code.ShortCodeList - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeList - """ - super(ShortCodeList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/ShortCodes'.format(**self._solution) - - def create(self, sid): - """ - Create 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 - """ - data = values.of({'Sid': sid, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return ShortCodeInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def stream(self, limit=None, page_size=None): - """ - Streams ShortCodeInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.short_code.ShortCodeInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists ShortCodeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.short_code.ShortCodeInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of ShortCodeInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodePage - """ - 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) - - def get_page(self, target_url): - """ - Retrieve a specific page of ShortCodeInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ShortCodePage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a ShortCodeContext - - :param sid: 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 - """ - return ShortCodeContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a ShortCodeContext - - :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 - """ - return ShortCodeContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ShortCodePage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, response, solution): - """ - Initialize the ShortCodePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: 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 - """ - super(ShortCodePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ShortCodeInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance - """ - return ShortCodeInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ShortCodeContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, service_sid, sid): - """ - Initialize the ShortCodeContext - - :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 - """ - super(ShortCodeContext, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/ShortCodes/{sid}'.format(**self._solution) - - def delete(self): - """ - Deletes the ShortCodeInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) - - def fetch(self): - """ - Fetch the ShortCodeInstance - - :returns: The fetched ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return ShortCodeInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - - def update(self, is_reserved=values.unset): - """ - Update the ShortCodeInstance - - :param bool is_reserved: Whether the short code should be reserved for manual assignment to participants only - - :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, ) - - return ShortCodeInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class ShortCodeInstance(InstanceResource): - """ PLEASE NOTE that this class contains 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'), - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: ShortCodeContext for this ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeContext - """ - if self._context is None: - self._context = ShortCodeContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context - - @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 service_sid(self): - """ - :returns: The SID of the resource's parent Service - :rtype: unicode - """ - return self._properties['service_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 short_code(self): - """ - :returns: The short code's number - :rtype: unicode - """ - return self._properties['short_code'] - - @property - def iso_country(self): - """ - :returns: The ISO Country Code - :rtype: unicode - """ - return self._properties['iso_country'] - - @property - def capabilities(self): - """ - :returns: The capabilities of the short code - :rtype: unicode - """ - return self._properties['capabilities'] - - @property - def url(self): - """ - :returns: The absolute URL of the ShortCode resource - :rtype: unicode - """ - return self._properties['url'] - - @property - def is_reserved(self): - """ - :returns: Whether the short code should be reserved for manual assignment to participants only - :rtype: bool - """ - return self._properties['is_reserved'] - - def delete(self): - """ - Deletes the ShortCodeInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def fetch(self): - """ - Fetch the ShortCodeInstance - - :returns: The fetched ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance - """ - return self._proxy.fetch() - - def update(self, is_reserved=values.unset): - """ - Update the ShortCodeInstance - - :param bool is_reserved: Whether the short code should be reserved for manual assignment to participants only - - :returns: The updated ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance - """ - return self._proxy.update(is_reserved=is_reserved, ) - - def __repr__(self): - """ - Provide 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/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..56b49fed77 --- /dev/null +++ b/twilio/rest/routes/v2/phone_number.py @@ -0,0 +1,485 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the PhoneNumberInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PhoneNumberInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = self._fetch() + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PhoneNumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = await self._fetch_async() + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + voice_region=voice_region, friendly_name=friendly_name + ) + return PhoneNumberInstance( + self._version, payload, phone_number=self._solution["phone_number"] + ) + + def update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the PhoneNumberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + voice_region=voice_region, friendly_name=friendly_name + ) + instance = PhoneNumberInstance( + self._version, payload, phone_number=self._solution["phone_number"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + voice_region=voice_region, friendly_name=friendly_name + ) + return PhoneNumberInstance( + self._version, payload, phone_number=self._solution["phone_number"] + ) + + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PhoneNumberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + voice_region=voice_region, friendly_name=friendly_name + ) + instance = PhoneNumberInstance( + self._version, payload, phone_number=self._solution["phone_number"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..dd4445f3b6 --- /dev/null +++ b/twilio/rest/routes/v2/sip_domain.py @@ -0,0 +1,485 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SipDomainInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SipDomainInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SipDomainInstance with HTTP info + + :param voice_region: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SipDomainInstance with HTTP info + + :param voice_region: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SipDomainInstance: + """ + Fetch the SipDomainInstance + + + :returns: The fetched SipDomainInstance + """ + payload, _, _ = self._fetch() + return SipDomainInstance( + self._version, + payload, + sip_domain=self._solution["sip_domain"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SipDomainInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SipDomainInstance( + self._version, + payload, + sip_domain=self._solution["sip_domain"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SipDomainInstance: + """ + Asynchronous coroutine to fetch the SipDomainInstance + + + :returns: The fetched SipDomainInstance + """ + payload, _, _ = await self._fetch_async() + return SipDomainInstance( + self._version, + payload, + sip_domain=self._solution["sip_domain"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SipDomainInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SipDomainInstance( + self._version, + payload, + sip_domain=self._solution["sip_domain"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + voice_region=voice_region, friendly_name=friendly_name + ) + return SipDomainInstance( + self._version, payload, sip_domain=self._solution["sip_domain"] + ) + + def update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SipDomainInstance and return response metadata + + :param voice_region: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + voice_region=voice_region, friendly_name=friendly_name + ) + instance = SipDomainInstance( + self._version, payload, sip_domain=self._solution["sip_domain"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + voice_region=voice_region, friendly_name=friendly_name + ) + return SipDomainInstance( + self._version, payload, sip_domain=self._solution["sip_domain"] + ) + + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SipDomainInstance and return response metadata + + :param voice_region: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + voice_region=voice_region, friendly_name=friendly_name + ) + instance = SipDomainInstance( + self._version, payload, sip_domain=self._solution["sip_domain"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..72d14c90bc --- /dev/null +++ b/twilio/rest/routes/v2/trunk.py @@ -0,0 +1,485 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the TrunkInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TrunkInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrunkInstance: + """ + Fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + payload, _, _ = self._fetch() + return TrunkInstance( + self._version, + payload, + sip_trunk_domain=self._solution["sip_trunk_domain"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrunkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TrunkInstance( + self._version, + payload, + sip_trunk_domain=self._solution["sip_trunk_domain"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TrunkInstance: + """ + Asynchronous coroutine to fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + payload, _, _ = await self._fetch_async() + return TrunkInstance( + self._version, + payload, + sip_trunk_domain=self._solution["sip_trunk_domain"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrunkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TrunkInstance( + self._version, + payload, + sip_trunk_domain=self._solution["sip_trunk_domain"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + voice_region=voice_region, friendly_name=friendly_name + ) + return TrunkInstance( + self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"] + ) + + def update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the TrunkInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + voice_region=voice_region, friendly_name=friendly_name + ) + instance = TrunkInstance( + self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + voice_region=voice_region, friendly_name=friendly_name + ) + return TrunkInstance( + self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"] + ) + + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TrunkInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + voice_region=voice_region, friendly_name=friendly_name + ) + instance = TrunkInstance( + self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 7b74fd6497..2210d07e2e 100644 --- a/twilio/rest/serverless/v1/service/__init__.py +++ b/twilio/rest/serverless/v1/service/__init__.py @@ -1,16 +1,25 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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 +27,1229 @@ 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. + 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 ServiceInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.serverless.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'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists ServiceInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.serverless.v1.service.ServiceInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_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.serverless.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() - :param str target_url: API-generated URL for the requested results page + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info - :returns: Page of ServiceInstance - :rtype: twilio.rest.serverless.v1.service.ServicePage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info - return ServicePage(self._version, response, self._solution) - def create(self, unique_name, friendly_name, include_credentials=values.unset, - ui_editable=values.unset): + :returns: ApiResponse with instance, status code, and headers """ - Create the ServiceInstance + return await self._proxy.fetch_with_http_info_async() - :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 + 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 - :returns: The created ServiceInstance - :rtype: twilio.rest.serverless.v1.service.ServiceInstance + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The updated ServiceInstance """ - data = values.of({ - 'UniqueName': unique_name, - 'FriendlyName': friendly_name, - 'IncludeCredentials': include_credentials, - 'UiEditable': ui_editable, - }) + return self._proxy.update( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def update_async( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance - return ServiceInstance(self._version, payload, ) + :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`. - def get(self, sid): + :returns: The updated ServiceInstance """ - Constructs a ServiceContext + return await self._proxy.update_async( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + + def update_with_http_info( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info - :param sid: The SID of the Service resource to fetch + :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.ServiceContext - :rtype: twilio.rest.serverless.v1.service.ServiceContext + :returns: ApiResponse with instance, status code, and headers """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - Constructs a ServiceContext + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) - :param sid: The SID of the Service resource to fetch + @property + def assets(self) -> AssetList: + """ + Access the assets + """ + return self._proxy.assets - :returns: twilio.rest.serverless.v1.service.ServiceContext - :rtype: twilio.rest.serverless.v1.service.ServiceContext + @property + def builds(self) -> BuildList: + """ + Access the builds """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.builds - def __repr__(self): + @property + def environments(self) -> EnvironmentList: + """ + Access the environments + """ + return self._proxy.environments + + @property + def functions(self) -> FunctionList: + """ + Access the functions + """ + return self._proxy.functions + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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 + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._assets: Optional[AssetList] = None + self._builds: Optional[BuildList] = None + self._environments: Optional[EnvironmentList] = None + self._functions: Optional[FunctionList] = None - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of ServiceInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :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): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the ServiceInstance and return response metadata -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. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the ServiceContext - :param Version version: Version that contains the resource - :param sid: The SID of the Service resource to fetch + headers = values.of({}) - :returns: twilio.rest.serverless.v1.service.ServiceContext - :rtype: twilio.rest.serverless.v1.service.ServiceContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(ServiceContext, self).__init__(version) + Asynchronous coroutine that deletes the ServiceInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) - # Dependents - self._environments = None - self._functions = None - self._assets = None - self._builds = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", 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, ) + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance and return response metadata - def delete(self): + + :returns: ApiResponse with instance, status code, and headers """ - Deletes the ServiceInstance + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def update(self, include_credentials=values.unset, friendly_name=values.unset, - ui_editable=values.unset): + def _update( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._update( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def update_with_http_info( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + :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`. - @property - def environments(self): + :returns: ApiResponse with instance, status code, and headers """ - Access the environments + payload, status_code, headers = self._update( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: twilio.rest.serverless.v1.service.environment.EnvironmentList - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentList + 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, + ) -> tuple: """ - if self._environments is None: - self._environments = EnvironmentList(self._version, service_sid=self._solution['sid'], ) - return self._environments + Internal async helper for update operation - @property - def functions(self): + Returns: + tuple: (payload, status_code, headers) """ - Access the functions - :returns: twilio.rest.serverless.v1.service.function.FunctionList - :rtype: twilio.rest.serverless.v1.service.function.FunctionList + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - if self._functions is None: - self._functions = FunctionList(self._version, service_sid=self._solution['sid'], ) - return self._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: The updated ServiceInstance + """ + payload, _, _ = await self._update_async( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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'), - } +class ServicePage(Page): - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance - @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 - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.serverless.v1.service.ServiceContext + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: """ - if self._context is None: - self._context = ServiceContext(self._version, 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 Service resource - :rtype: unicode + return "" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['sid'] + Initialize the ServiceList + + :param version: Version that contains the resource - @property - def account_sid(self): """ - :returns: The SID of the Account that created the Service resource - :rtype: unicode + 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, + ) -> tuple: """ - return self._properties['account_sid'] + Internal helper for create operation - @property - def friendly_name(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The string that you assigned to describe the Service resource - :rtype: unicode + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['friendly_name'] + Create the ServiceInstance - @property - def unique_name(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: An application-defined string that uniquely identifies the Service resource - :rtype: unicode + payload, _, _ = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + include_credentials=include_credentials, + ui_editable=ui_editable, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: str, + friendly_name: str, + include_credentials: Union[bool, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['unique_name'] + Create the ServiceInstance and return response metadata - @property - def include_credentials(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: ApiResponse with instance, status code, and headers """ - :returns: Whether to inject Account credentials into a function invocation context - :rtype: bool + payload, status_code, headers = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + include_credentials=include_credentials, + ui_editable=ui_editable, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['include_credentials'] + Asynchronously create the ServiceInstance - @property - def ui_editable(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: Whether the Service's properties and subresources can be edited via the UI - :rtype: bool + payload, _, _ = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + include_credentials=include_credentials, + ui_editable=ui_editable, + ) + return ServiceInstance(self._version, payload) + + async def create_with_http_info_async( + self, + unique_name: str, + friendly_name: str, + include_credentials: Union[bool, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['ui_editable'] + Asynchronously create the ServiceInstance and return response metadata - @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: ApiResponse with instance, status code, and headers """ - :returns: The ISO 8601 date and time in GMT when the Service resource was created - :rtype: datetime + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + include_credentials=include_credentials, + ui_editable=ui_editable, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 Service 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['url'] + Streams ServiceInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The URLs of the Service's nested resources - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['links'] + Asynchronously streams ServiceInstance and returns headers from first page + - 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: tuple of (generator, status_code, headers) where generator yields instances """ - Fetch the ServiceInstance + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :returns: The fetched ServiceInstance - :rtype: twilio.rest.serverless.v1.service.ServiceInstance + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: """ - return self._proxy.fetch() + 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 """ - Deletes the ServiceInstance - :returns: True if delete succeeds, False otherwise - :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[ServiceInstance]: """ - return self._proxy.delete() + 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) - def update(self, include_credentials=values.unset, friendly_name=values.unset, - ui_editable=values.unset): + :returns: list that will contain up to limit results """ - 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 + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - :returns: The updated ServiceInstance - :rtype: twilio.rest.serverless.v1.service.ServiceInstance + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.update( - include_credentials=include_credentials, - friendly_name=friendly_name, - ui_editable=ui_editable, + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def environments(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Access the environments + Asynchronously lists ServiceInstance and returns headers from first page + - :returns: twilio.rest.serverless.v1.service.environment.EnvironmentList - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentList + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._proxy.environments + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def functions(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 functions + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.serverless.v1.service.function.FunctionList - :rtype: twilio.rest.serverless.v1.service.function.FunctionList + :param page_token: PageToken provided by the API + :param page_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.functions + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def assets(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 assets + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.serverless.v1.service.asset.AssetList - :rtype: twilio.rest.serverless.v1.service.asset.AssetList + :param page_token: PageToken provided by the API + :param page_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.assets + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def builds(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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Access the builds + Retrieve a single page with response metadata + - :returns: twilio.rest.serverless.v1.service.build.BuildList - :rtype: twilio.rest.serverless.v1.service.build.BuildList + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers """ - return self._proxy.builds + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The `sid` or `unique_name` of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The `sid` or `unique_name` of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 d660ccf753..8eae827c10 100644 --- a/twilio/rest/serverless/v1/service/asset/__init__.py +++ b/twilio/rest/serverless/v1/service/asset/__init__.py @@ -1,460 +1,1074 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +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") - def __init__(self, version, service_sid): + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[AssetContext] = None + + @property + def _proxy(self) -> "AssetContext": """ - Initialize the AssetList + 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 Asset resource is associated with + :returns: AssetContext for this AssetInstance + """ + if self._context is None: + self._context = AssetContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.serverless.v1.service.asset.AssetList - :rtype: twilio.rest.serverless.v1.service.asset.AssetList + def delete(self) -> bool: """ - super(AssetList, self).__init__(version) + Deletes the AssetInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Assets'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + 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 AssetInstance - :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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssetInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists AssetInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssetInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.serverless.v1.service.asset.AssetInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_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, }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "AssetInstance": + """ + Asynchronous coroutine to fetch the AssetInstance - return AssetPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched AssetInstance """ - Retrieve a specific page of AssetInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssetInstance with HTTP info - :returns: Page of AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() - return AssetPage(self._version, response, self._solution) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssetInstance with HTTP info - def create(self, friendly_name): + + :returns: ApiResponse with instance, status code, and headers """ - Create the AssetInstance + return await self._proxy.fetch_with_http_info_async() - :param unicode friendly_name: A string to describe the Asset resource + def update(self, friendly_name: str) -> "AssetInstance": + """ + Update the AssetInstance - :returns: The created AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetInstance + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The updated AssetInstance """ - data = values.of({'FriendlyName': friendly_name, }) + return self._proxy.update( + friendly_name=friendly_name, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def update_async(self, friendly_name: str) -> "AssetInstance": + """ + Asynchronous coroutine to update the AssetInstance - return AssetInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. - def get(self, sid): + :returns: The updated AssetInstance """ - Constructs a AssetContext + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - :param sid: The SID that identifies the Asset resource to fetch + def update_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Update the AssetInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers """ - return AssetContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: """ - Constructs a AssetContext + Asynchronous coroutine to update the AssetInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return AssetContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) - def __repr__(self): + @property + def asset_versions(self) -> AssetVersionList: + """ + Access the asset_versions + """ + return self._proxy.asset_versions + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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) + + self._asset_versions: Optional[AssetVersionList] = None - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of AssetInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.serverless.v1.service.asset.AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetInstance + def delete(self) -> bool: """ - return AssetInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the AssetInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the AssetInstance and return response metadata -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. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the AssetContext + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :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 + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.serverless.v1.service.asset.AssetContext - :rtype: twilio.rest.serverless.v1.service.asset.AssetContext + async def delete_async(self) -> bool: """ - super(AssetContext, self).__init__(version) + Asynchronous coroutine that deletes the AssetInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Assets/{sid}'.format(**self._solution) - # Dependents - self._asset_versions = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssetInstance and return response metadata + - def fetch(self): + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AssetInstance: """ Fetch the AssetInstance + :returns: The fetched AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssetInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + async def fetch_async(self) -> AssetInstance: + """ + Asynchronous coroutine to fetch the AssetInstance + + + :returns: The fetched AssetInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the AssetInstance + Asynchronous coroutine to fetch the AssetInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def update(self, friendly_name): + def _update(self, friendly_name: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, friendly_name: str) -> 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 updated AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetInstance """ - data = values.of({'FriendlyName': friendly_name, }) + payload, _, _ = self._update(friendly_name=friendly_name) + return AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def update_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Update the AssetInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for update operation + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async(self, friendly_name: str) -> AssetInstance: + """ + Asynchronous coroutine to update the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The updated AssetInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) 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"], + ) + + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronous coroutine to update the AssetInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 get_instance(self, payload: Dict[str, Any]) -> AssetInstance: + """ + Build an instance of AssetInstance - def __init__(self, version, payload, service_sid, sid=None): + :param payload: Payload response from the API """ - Initialize the AssetInstance - :returns: twilio.rest.serverless.v1.service.asset.AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetInstance + return AssetInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: """ - super(AssetInstance, 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'), - '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 "" + + +class AssetList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the AssetList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Asset resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/Assets".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create(self, friendly_name: str) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: AssetContext for this AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, friendly_name: str) -> AssetInstance: """ - if self._context is None: - self._context = AssetContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the AssetInstance - @property - def 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 unique string that identifies the Asset resource - :rtype: unicode + payload, _, _ = self._create(friendly_name=friendly_name) + return AssetInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info(self, friendly_name: str) -> ApiResponse: """ - return self._properties['sid'] + Create the AssetInstance and return response metadata - @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: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Account that created the Asset resource - :rtype: unicode + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = AssetInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, friendly_name: str) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for create operation - @property - def service_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, friendly_name: str) -> AssetInstance: """ - return self._properties['service_sid'] + Asynchronously create the AssetInstance - @property - def friendly_name(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 string that you assigned to describe the Asset resource - :rtype: unicode + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return AssetInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: """ - return self._properties['friendly_name'] + Asynchronously create the AssetInstance and return response metadata - @property - def date_created(self): + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The ISO 8601 date and time in GMT when the Asset resource was created - :rtype: datetime + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = AssetInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssetInstance]: """ - return self._properties['date_created'] + 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_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 Asset 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[AssetInstance]: """ - return self._properties['date_updated'] + 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 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 Asset 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['url'] + Streams AssetInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The links to the nested resources of the asset - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['links'] + Asynchronously streams AssetInstance and returns headers from first 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 fetch(self): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Fetch the AssetInstance + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :returns: The fetched AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetInstance + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssetInstance]: """ - return self._proxy.fetch() + Lists AssetInstance 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 """ - Deletes the AssetInstance - :returns: True if delete succeeds, False otherwise - :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[AssetInstance]: """ - return self._proxy.delete() + Asynchronously lists AssetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - def update(self, friendly_name): + :returns: list that will contain up to limit results """ - Update the AssetInstance - :param unicode friendly_name: A string to describe the Asset resource + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - :returns: The updated AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetInstance + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.update(friendly_name, ) + Lists AssetInstance and returns headers from first page - @property - def asset_versions(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: ApiResponse with list of instances, status code, and headers """ - Access the asset_versions + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionList - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionList + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.asset_versions + Asynchronously lists AssetInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssetPage: + """ + Retrieve a single page of AssetInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssetInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssetPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssetPage: + """ + Asynchronously retrieve a single page of AssetInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssetInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssetPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssetPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssetPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssetPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssetPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> AssetPage: + """ + Retrieve a specific page of AssetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssetInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssetPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> AssetPage: + """ + Asynchronously retrieve a specific page of AssetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssetInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssetPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> AssetContext: + """ + Constructs a AssetContext + + :param sid: The SID that identifies the Asset resource to update. + """ + return AssetContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> AssetContext: + """ + Constructs a AssetContext + + :param sid: The SID that identifies the Asset resource to update. + """ + return AssetContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 201d5b4f32..a8d50afe6b 100644 --- a/twilio/rest/serverless/v1/service/asset/asset_version.py +++ b/twilio/rest/serverless/v1/service/asset/asset_version.py @@ -1,395 +1,713 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 - """ - super(AssetVersionList, self).__init__(version) + self._solution = { + "service_sid": service_sid, + "asset_sid": asset_sid, + "sid": sid or self.sid, + } - # Path Solution - self._solution = {'service_sid': service_sid, 'asset_sid': asset_sid, } - self._uri = '/Services/{service_sid}/Assets/{asset_sid}/Versions'.format(**self._solution) + self._context: Optional[AssetVersionContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "AssetVersionContext": """ - 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. + 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: 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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionInstance] + def fetch(self) -> "AssetVersionInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the AssetVersionInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched AssetVersionInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the AssetVersionInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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 """ - 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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of AssetVersionInstance records from the API. - Request is executed immediately + Fetch the AssetVersionInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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 + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Asynchronous coroutine to fetch the AssetVersionInstance with HTTP info - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return AssetVersionPage(self._version, response, self._solution) + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() - def get_page(self, target_url): + def __repr__(self) -> str: """ - Retrieve a specific page of AssetVersionInstance 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 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): + """ + Initialize the AssetVersionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Asset Version resource from. + :param asset_sid: The SID of the Asset resource that is the parent of the Asset Version resource to fetch. + :param sid: The SID of the Asset Version resource to fetch. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 ) - return AssetVersionPage(self._version, response, self._solution) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - def get(self, sid): + Returns: + tuple: (payload, status_code, headers) """ - Constructs a AssetVersionContext - :param sid: The SID that identifies the Asset Version resource to fetch + headers = values.of({}) - :returns: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionContext - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionContext + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AssetVersionInstance: """ - return AssetVersionContext( + Fetch the AssetVersionInstance + + + :returns: The fetched AssetVersionInstance + """ + payload, _, _ = self._fetch() + 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a AssetVersionContext + Fetch the AssetVersionInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return AssetVersionContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -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. """ + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + async def fetch_async(self) -> AssetVersionInstance: """ - Initialize the AssetVersionPage + Asynchronous coroutine to fetch the AssetVersionInstance + - :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: The fetched AssetVersionInstance + """ + payload, _, _ = await self._fetch_async() + return AssetVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionPage - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionPage + async def fetch_with_http_info_async(self) -> ApiResponse: """ - super(AssetVersionPage, self).__init__(version, response) + Asynchronous coroutine to fetch the AssetVersionInstance and return response metadata - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of AssetVersionInstance + payload, status_code, headers = await self._fetch_async() + instance = AssetVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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) + - :param dict payload: Payload response from the API +class AssetVersionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssetVersionInstance: + """ + Build an instance of AssetVersionInstance - :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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AssetVersionInstance and returns headers from first page - class Visibility(object): - PUBLIC = "public" - PRIVATE = "private" - PROTECTED = "protected" - def __init__(self, version, payload, service_sid, asset_sid, sid=None): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Initialize the AssetVersionInstance + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionInstance - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionInstance + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(AssetVersionInstance, self).__init__(version) + Asynchronously streams AssetVersionInstance and returns headers from first page - # 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'], - } + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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: tuple of (generator, status_code, headers) where generator yields instances """ - 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_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :returns: AssetVersionContext for this AssetVersionInstance - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionContext + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[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'], + Lists AssetVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssetVersionInstance]: """ - :returns: The unique string that identifies the Asset Version resource - :rtype: unicode + Asynchronously lists AssetVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['sid'] - @property - def account_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Account that created the Asset Version resource - :rtype: unicode + Lists AssetVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['account_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def service_sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Service that the Asset Version resource is associated with - :rtype: unicode + Asynchronously lists AssetVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['service_sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def asset_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, + ) -> AssetVersionPage: """ - :returns: The SID of the Asset resource that is the parent of the asset version - :rtype: unicode + 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['asset_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def path(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 AssetVersionPage(self._version, response, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The access control that determines how the asset version can be accessed - :rtype: AssetVersionInstance.Visibility + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssetVersionPage, status code, and headers """ - return self._properties['visibility'] + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssetVersionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The ISO 8601 date and time in GMT when the Asset Version resource was created - :rtype: datetime + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssetVersionPage, status code, and headers """ - return self._properties['date_created'] + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssetVersionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> AssetVersionPage: """ - :returns: The absolute URL of the Asset Version resource - :rtype: unicode + 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['url'] + response = self._version.domain.twilio.request("GET", target_url) + return AssetVersionPage(self._version, response, solution=self._solution) - def fetch(self): + async def get_page_async(self, target_url: str) -> AssetVersionPage: """ - Fetch the AssetVersionInstance + Asynchronously retrieve a specific page of AssetVersionInstance records from the API. + Request is executed immediately - :returns: The fetched AssetVersionInstance - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssetVersionInstance """ - return self._proxy.fetch() + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssetVersionPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> AssetVersionContext: + """ + Constructs a AssetVersionContext + + :param sid: The SID of the Asset Version resource to fetch. + """ + return AssetVersionContext( + self._version, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AssetVersionContext: + """ + Constructs a AssetVersionContext + + :param sid: The SID of the Asset Version resource to fetch. + """ + return AssetVersionContext( + self._version, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 66fdafcc08..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'], limits['page_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..bc54d0b495 --- /dev/null +++ b/twilio/rest/serverless/v1/service/build/__init__.py @@ -0,0 +1,976 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BuildInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BuildInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BuildInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BuildInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + + headers = values.of({}) + + + + return self._version.delete_with_response_info(method='DELETE', uri=self._uri, headers=headers) + + def delete(self) -> bool: + """ + Deletes the BuildInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BuildInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + + + return await self._version.delete_with_response_info_async(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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BuildInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + + headers = values.of({}) + + + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info(method='GET', uri=self._uri, headers=headers) + + def fetch(self) -> BuildInstance: + """ + Fetch the BuildInstance + + + :returns: The fetched BuildInstance + """ + payload, _, _ = self._fetch() + return BuildInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BuildInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BuildInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + + headers = values.of({}) + + + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async(method='GET', uri=self._uri, headers=headers) + + async def fetch_async(self) -> BuildInstance: + """ + Asynchronous coroutine to fetch the BuildInstance + + + :returns: The fetched BuildInstance + """ + payload, _, _ = await self._fetch_async() + return BuildInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BuildInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BuildInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + + @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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + + return self._version.create_with_response_info(method='POST', uri=self._uri, data=data, headers=headers) + + 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 + """ + payload, _, _ = self._create(asset_versions=asset_versions, function_versions=function_versions, dependencies=dependencies, runtime=runtime) + return BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) + + def create_with_http_info(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) -> ApiResponse: + """ + Create the BuildInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(asset_versions=asset_versions, function_versions=function_versions, dependencies=dependencies, runtime=runtime) + instance = BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + + return await self._version.create_with_response_info_async(method='POST', uri=self._uri, data=data, headers=headers) + + 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 + """ + payload, _, _ = await self._create_async(asset_versions=asset_versions, function_versions=function_versions, dependencies=dependencies, runtime=runtime) + return BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) + + async def create_with_http_info_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) -> ApiResponse: + """ + Asynchronously create the BuildInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(asset_versions=asset_versions, function_versions=function_versions, dependencies=dependencies, runtime=runtime) + instance = BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + + 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 stream_with_http_info(self, + + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BuildInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_size=limits['page_size'] + ) + + generator = self._version.stream(page_response.data, limits['limit']) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async(self, + + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BuildInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits['page_size'] + ) + + generator = self._version.stream_async(page_response.data, limits['limit']) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info(self, + + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BuildInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async(self, + + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BuildInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info(self, + + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BuildPage, status code, and headers + """ + data = values.of({ + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + + headers["Accept"] = "application/json" + + + response, status_code, response_headers = self._version.page_with_response_info(method='GET', uri=self._uri, params=data, headers=headers) + page = BuildPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async(self, + + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BuildPage, status code, and headers + """ + data = values.of({ + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + + headers["Accept"] = "application/json" + + + response, status_code, response_headers = await self._version.page_with_response_info_async(method='GET', uri=self._uri, params=data, headers=headers) + page = BuildPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..03a81818c1 --- /dev/null +++ b/twilio/rest/serverless/v1/service/build/build_status.py @@ -0,0 +1,304 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BuildStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BuildStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + + headers = values.of({}) + + + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info(method='GET', uri=self._uri, headers=headers) + + def fetch(self) -> BuildStatusInstance: + """ + Fetch the BuildStatusInstance + + + :returns: The fetched BuildStatusInstance + """ + payload, _, _ = self._fetch() + return BuildStatusInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BuildStatusInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BuildStatusInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + + headers = values.of({}) + + + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async(method='GET', uri=self._uri, headers=headers) + + async def fetch_async(self) -> BuildStatusInstance: + """ + Asynchronous coroutine to fetch the BuildStatusInstance + + + :returns: The fetched BuildStatusInstance + """ + payload, _, _ = await self._fetch_async() + return BuildStatusInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BuildStatusInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BuildStatusInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 ceab0ec595..f5817a338c 100644 --- a/twilio/rest/serverless/v1/service/environment/__init__.py +++ b/twilio/rest/serverless/v1/service/environment/__init__.py @@ -1,513 +1,988 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +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") - def __init__(self, version, service_sid): - """ - Initialize the EnvironmentList + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the Environment resource is associated with + 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) + 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}/Environments'.format(**self._solution) + :returns: EnvironmentContext for this EnvironmentInstance + """ + if self._context is None: + self._context = EnvironmentContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def delete(self) -> bool: """ - 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. + Deletes the EnvironmentInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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 """ - 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 EnvironmentInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - Lists EnvironmentInstance 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EnvironmentInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.serverless.v1.service.environment.EnvironmentInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.delete_with_http_info() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of EnvironmentInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the EnvironmentInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with success boolean, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.delete_with_http_info_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def fetch(self) -> "EnvironmentInstance": + """ + Fetch the EnvironmentInstance - return EnvironmentPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched EnvironmentInstance """ - Retrieve a specific page of EnvironmentInstance 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 EnvironmentInstance - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentPage + async def fetch_async(self) -> "EnvironmentInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronous coroutine to fetch the EnvironmentInstance - return EnvironmentPage(self._version, response, self._solution) - def create(self, unique_name, domain_suffix=values.unset): + :returns: The fetched EnvironmentInstance """ - 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 + return await self._proxy.fetch_async() - :returns: The created EnvironmentInstance - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentInstance + def fetch_with_http_info(self) -> ApiResponse: """ - data = values.of({'UniqueName': unique_name, 'DomainSuffix': domain_suffix, }) + Fetch the EnvironmentInstance with HTTP info - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return EnvironmentInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() - def get(self, sid): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Constructs a EnvironmentContext + Asynchronous coroutine to fetch the EnvironmentInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return EnvironmentContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.fetch_with_http_info_async() - def __call__(self, sid): + @property + def deployments(self) -> DeploymentList: """ - Constructs a EnvironmentContext + Access the deployments + """ + return self._proxy.deployments - :param sid: The SID of the Environment resource to fetch + @property + def logs(self) -> LogList: + """ + Access the logs + """ + return self._proxy.logs - :returns: twilio.rest.serverless.v1.service.environment.EnvironmentContext - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentContext + @property + def variables(self) -> VariableList: + """ + 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 + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Environments/{sid}".format( + **self._solution + ) + + self._deployments: Optional[DeploymentList] = None + self._logs: Optional[LogList] = None + self._variables: Optional[VariableList] = None - def get_instance(self, payload): + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of EnvironmentInstance - :param dict payload: Payload response from the API + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :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): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the EnvironmentInstance and return response metadata -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. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the EnvironmentContext + Internal async helper for delete operation - :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: + tuple: (success_boolean, status_code, headers) + """ - :returns: twilio.rest.serverless.v1.service.environment.EnvironmentContext - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentContext + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(EnvironmentContext, self).__init__(version) + Asynchronous coroutine that deletes the EnvironmentInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Environments/{sid}'.format(**self._solution) - # Dependents - self._variables = None - self._deployments = None - self._logs = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EnvironmentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - def fetch(self): + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + 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, ) - + payload, _, _ = self._fetch() 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Deletes the EnvironmentInstance + Fetch the EnvironmentInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = self._fetch() + instance = EnvironmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def variables(self): + async def _fetch_async(self) -> tuple: """ - Access the variables + Internal async helper for fetch operation - :returns: twilio.rest.serverless.v1.service.environment.variable.VariableList - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableList + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> EnvironmentInstance: + """ + Asynchronous coroutine to fetch the EnvironmentInstance + + + :returns: The fetched EnvironmentInstance + """ + payload, _, _ = await self._fetch_async() + return EnvironmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EnvironmentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EnvironmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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'), +class EnvironmentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EnvironmentInstance: + """ + Build an instance of EnvironmentInstance + + :param payload: Payload response from the API + """ + + return EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EnvironmentList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the EnvironmentList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Environment resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/Environments".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: EnvironmentContext for this EnvironmentInstance - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> EnvironmentInstance: """ - if self._context is None: - self._context = EnvironmentContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the EnvironmentInstance - @property - def sid(self): + :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 """ - :returns: The unique string that identifies the Environment resource - :rtype: unicode + payload, _, _ = self._create( + unique_name=unique_name, domain_suffix=domain_suffix + ) + return EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> ApiResponse: """ - return self._properties['sid'] + Create the EnvironmentInstance and return response metadata - @property - def account_sid(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Account that created the Environment resource - :rtype: unicode + payload, status_code, headers = self._create( + unique_name=unique_name, domain_suffix=domain_suffix + ) + instance = EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for create operation - @property - def service_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the Service that the Environment resource is associated with - :rtype: unicode + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> EnvironmentInstance: """ - return self._properties['service_sid'] + Asynchronously create the EnvironmentInstance - @property - def build_sid(self): + :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 """ - :returns: The SID of the build deployed in the environment - :rtype: unicode + payload, _, _ = await self._create_async( + unique_name=unique_name, domain_suffix=domain_suffix + ) + return EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> ApiResponse: """ - return self._properties['build_sid'] + Asynchronously create the EnvironmentInstance and return response metadata - @property - def unique_name(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: An application-defined string that uniquely identifies the Environment resource - :rtype: unicode + payload, status_code, headers = await self._create_async( + unique_name=unique_name, domain_suffix=domain_suffix + ) + instance = EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EnvironmentInstance]: """ - return self._properties['unique_name'] + 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. - @property - def domain_suffix(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: A URL-friendly name that represents the environment - :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[EnvironmentInstance]: """ - return self._properties['domain_suffix'] + 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. - @property - def domain_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 base domain name for all Functions and Assets deployed in the environment - :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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['domain_name'] + Streams EnvironmentInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The ISO 8601 date and time in GMT when the Environment resource was created - :rtype: datetime + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_created'] + Asynchronously streams EnvironmentInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The ISO 8601 date and time in GMT when the Environment resource was last updated - :rtype: datetime + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EnvironmentInstance]: """ - return self._properties['date_updated'] + Lists EnvironmentInstance 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 Environment 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[EnvironmentInstance]: """ - return self._properties['url'] + 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. - @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 the environment's nested resources - :rtype: unicode + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['links'] + Lists EnvironmentInstance and returns headers from first page + - 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: ApiResponse with list of instances, status code, and headers """ - Fetch the EnvironmentInstance + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: The fetched EnvironmentInstance - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentInstance + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.fetch() + Asynchronously lists EnvironmentInstance and returns headers from first page + - 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: ApiResponse with list of instances, status code, and headers """ - Deletes the EnvironmentInstance + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + 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: """ - return self._proxy.delete() + Retrieve a single page of EnvironmentInstance records from the API. + Request is executed immediately - @property - def variables(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 EnvironmentInstance """ - Access the variables + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - :returns: twilio.rest.serverless.v1.service.environment.variable.VariableList - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableList + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EnvironmentPage(self._version, response, solution=self._solution) + + async def 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: """ - return self._proxy.variables + Asynchronously retrieve a single page of EnvironmentInstance records from the API. + Request is executed immediately - @property - def deployments(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 EnvironmentInstance """ - Access the deployments + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentList - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentList + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EnvironmentPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.deployments + Retrieve a single page with response metadata - @property - def logs(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: ApiResponse with EnvironmentPage, status code, and headers """ - Access the logs + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EnvironmentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - :returns: twilio.rest.serverless.v1.service.environment.log.LogList - :rtype: twilio.rest.serverless.v1.service.environment.log.LogList + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.logs + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EnvironmentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EnvironmentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> EnvironmentPage: + """ + Retrieve a specific page of EnvironmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EnvironmentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EnvironmentPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> EnvironmentPage: + """ + Asynchronously retrieve a specific page of EnvironmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EnvironmentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EnvironmentPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> EnvironmentContext: + """ + Constructs a EnvironmentContext + + :param sid: The SID of the Environment resource to fetch. + """ + return EnvironmentContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> EnvironmentContext: + """ + Constructs a EnvironmentContext + + :param sid: The SID of the Environment resource to fetch. + """ + return EnvironmentContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 4ae403add9..65fecb891a 100644 --- a/twilio/rest/serverless/v1/service/environment/deployment.py +++ b/twilio/rest/serverless/v1/service/environment/deployment.py @@ -1,410 +1,859 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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. """ +class DeploymentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Deployment resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Deployment resource. + :ivar service_sid: The SID of the Service that the Deployment resource is associated with. + :ivar environment_sid: The SID of the Environment for the Deployment. + :ivar build_sid: The SID of the Build for the deployment. + :ivar date_created: The date and time in GMT when the Deployment resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Deployment resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Deployment resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + environment_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.environment_sid: Optional[str] = payload.get("environment_sid") + self.build_sid: Optional[str] = payload.get("build_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid or self.sid, + } + + self._context: Optional[DeploymentContext] = None - def __init__(self, version, service_sid, environment_sid): + @property + def _proxy(self) -> "DeploymentContext": """ - Initialize the DeploymentList + 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 Deployment resource is associated with - :param environment_sid: The SID of the environment for the deployment + :returns: DeploymentContext for this DeploymentInstance + """ + if self._context is None: + self._context = DeploymentContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentList - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentList + def fetch(self) -> "DeploymentInstance": """ - super(DeploymentList, self).__init__(version) + Fetch the DeploymentInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'environment_sid': environment_sid, } - self._uri = '/Services/{service_sid}/Environments/{environment_sid}/Deployments'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "DeploymentInstance": + """ + Asynchronous coroutine to fetch the DeploymentInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance] + + :returns: The fetched DeploymentInstance """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.fetch_async() - page = self.page(page_size=limits['page_size'], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DeploymentInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with instance, status code, and headers """ - Lists DeploymentInstance 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_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeploymentInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance] + + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_with_http_info_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 + 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 DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentPage + +class DeploymentContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, environment_sid: str, sid: str + ): + """ + Initialize the DeploymentContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Deployment resource from. + :param environment_sid: The SID of the Environment used by the Deployment to fetch. + :param sid: The SID that identifies the Deployment resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Environments/{environment_sid}/Deployments/{sid}".format( + **self._solution + ) + + def _fetch(self) -> tuple: """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Internal helper for fetch operation - response = self._version.page(method='GET', uri=self._uri, params=data, ) + Returns: + tuple: (payload, status_code, headers) + """ - return DeploymentPage(self._version, response, self._solution) + headers = values.of({}) - def get_page(self, target_url): + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DeploymentInstance: """ - Retrieve a specific page of DeploymentInstance records from the API. - Request is executed immediately + Fetch the DeploymentInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentPage + :returns: The fetched DeploymentInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + payload, _, _ = self._fetch() + return DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], ) - return DeploymentPage(self._version, response, self._solution) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DeploymentInstance and return response metadata + - def create(self, build_sid=values.unset): + :returns: ApiResponse with instance, status code, and headers """ - Create the DeploymentInstance + payload, status_code, headers = self._fetch() + instance = DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param unicode build_sid: The SID of the build for the deployment + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: The created DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DeploymentInstance: """ - data = values.of({'BuildSid': build_sid, }) + Asynchronous coroutine to fetch the DeploymentInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :returns: The fetched DeploymentInstance + """ + payload, _, _ = await self._fetch_async() 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_with_http_info_async(self) -> ApiResponse: """ - Constructs a DeploymentContext + Asynchronous coroutine to fetch the DeploymentInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return DeploymentContext( + payload, status_code, headers = await self._fetch_async() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __call__(self, sid): + def __repr__(self) -> str: """ - Constructs a DeploymentContext + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The SID 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 +class DeploymentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DeploymentInstance: """ - return DeploymentContext( + Build an instance of DeploymentInstance + + :param payload: Payload response from the API + """ + + 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"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + 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. """ +class DeploymentList(ListResource): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, environment_sid: str): """ - Initialize the DeploymentPage + Initialize the DeploymentList - :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 + :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.DeploymentPage - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentPage """ - super(DeploymentPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + } + self._uri = ( + "/Services/{service_sid}/Environments/{environment_sid}/Deployments".format( + **self._solution + ) + ) - def get_instance(self, payload): + def _create( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> tuple: """ - Build an instance of DeploymentInstance + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "BuildSid": build_sid, + "IsPlugin": serialize.boolean_to_string(is_plugin), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :param dict payload: Payload response from the API + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> DeploymentInstance: """ + Create the DeploymentInstance + + :param build_sid: The SID of the Build for the Deployment. + :param is_plugin: Whether the Deployment is a plugin. + + :returns: The created DeploymentInstance + """ + payload, _, _ = self._create(build_sid=build_sid, is_plugin=is_plugin) 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 create_with_http_info( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - Provide a friendly representation + Create the DeploymentInstance and return response metadata - :returns: Machine friendly representation - :rtype: str - """ - return '' + :param build_sid: The SID of the Build for the Deployment. + :param is_plugin: Whether the Deployment is a plugin. + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + build_sid=build_sid, is_plugin=is_plugin + ) + instance = DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) -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. """ + async def _create_async( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation - def __init__(self, version, service_sid, environment_sid, sid): + Returns: + tuple: (payload, status_code, headers) """ - Initialize the DeploymentContext - :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 + 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" - :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> DeploymentInstance: """ - super(DeploymentContext, self).__init__(version) + Asynchronously create the DeploymentInstance - # 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) + :param build_sid: The SID of the Build for the Deployment. + :param is_plugin: Whether the Deployment is a plugin. - def fetch(self): + :returns: The created DeploymentInstance """ - Fetch the DeploymentInstance + payload, _, _ = await self._create_async( + build_sid=build_sid, is_plugin=is_plugin + ) + return DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) - :returns: The fetched DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance + async def create_with_http_info_async( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronously create the DeploymentInstance and return response metadata - return DeploymentInstance( + :param build_sid: The SID of the Build for the Deployment. + :param is_plugin: Whether the Deployment is a plugin. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + build_sid=build_sid, is_plugin=is_plugin + ) + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DeploymentInstance]: """ - Provide a friendly representation + 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: 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 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. """ + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DeploymentInstance]: + """ + Asynchronously streams DeploymentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def __init__(self, version, payload, service_sid, environment_sid, sid=None): + :returns: Generator that will yield up to limit results """ - Initialize the DeploymentInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(DeploymentInstance, self).__init__(version) + Streams DeploymentInstance and returns headers from first page - # 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'), - } - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'environment_sid': environment_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: tuple of (generator, status_code, headers) where generator yields instances """ - 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_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: DeploymentContext for this DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - 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'], + Asynchronously streams DeploymentInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeploymentInstance]: + """ + Lists DeploymentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeploymentInstance]: """ - :returns: The unique string that identifies the Deployment resource - :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['sid'] - @property - def account_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Account that created the Deployment resource - :rtype: unicode + Lists DeploymentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['account_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def service_sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DeploymentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - :returns: The SID of the Service that the Deployment resource is associated with - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['service_sid'] + Retrieve a single page of DeploymentInstance records from the API. + Request is executed immediately - @property - def environment_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 DeploymentInstance """ - :returns: The SID of the environment for the deployment - :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 DeploymentPage(self._version, response, solution=self._solution) + + async def 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: """ - return self._properties['environment_sid'] + Asynchronously retrieve a single page of DeploymentInstance records from the API. + Request is executed immediately - @property - def build_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 DeploymentInstance """ - :returns: The SID of the build for the deployment - :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 DeploymentPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['build_sid'] + Retrieve a single page with response metadata - @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: ApiResponse with DeploymentPage, status code, and headers """ - :returns: The ISO 8601 date and time in GMT when the Deployment 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DeploymentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_created'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with DeploymentPage, status code, and headers """ - :returns: The ISO 8601 date and time in GMT when the Deployment 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DeploymentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> DeploymentPage: """ - return self._properties['date_updated'] + Retrieve a specific page of DeploymentInstance 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 DeploymentInstance """ - :returns: The absolute URL of the Deployment resource - :rtype: unicode + response = self._version.domain.twilio.request("GET", target_url) + return DeploymentPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> DeploymentPage: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of DeploymentInstance """ - Fetch the DeploymentInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return DeploymentPage(self._version, response, solution=self._solution) - :returns: The fetched DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance + def get(self, sid: str) -> DeploymentContext: """ - return self._proxy.fetch() + Constructs a DeploymentContext + + :param sid: The SID that identifies the Deployment resource to fetch. + """ + return DeploymentContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> DeploymentContext: + """ + Constructs a DeploymentContext + + :param sid: The SID that identifies the Deployment resource to fetch. + """ + return DeploymentContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 926aeaf1d5..30ff705ac5 100644 --- a/twilio/rest/serverless/v1/service/environment/log.py +++ b/twilio/rest/serverless/v1/service/environment/log.py @@ -1,453 +1,833 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + """ + :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: The log 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[str] = 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") - def __init__(self, version, service_sid, environment_sid): - """ - Initialize the LogList + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid or self.sid, + } - :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 + self._context: Optional[LogContext] = None - :returns: twilio.rest.serverless.v1.service.environment.log.LogList - :rtype: twilio.rest.serverless.v1.service.environment.log.LogList + @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'], limits['page_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) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the LogInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.serverless.v1.service.environment.log.LogInstance] + + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream( - function_sid=function_sid, - start_date=start_date, - end_date=end_date, - limit=limit, - page_size=page_size, - )) + return self._proxy.fetch_with_http_info() - 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of LogInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the LogInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - 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, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + return await self._proxy.fetch_with_http_info_async() - return LogPage(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 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 str target_url: API-generated URL for the requested results page - :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 + ): """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Initialize the LogContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Log resource from. + :param environment_sid: The SID of the environment with the Log resource to fetch. + :param sid: The SID of the Log resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Environments/{environment_sid}/Logs/{sid}".format( + **self._solution + ) ) - return LogPage(self._version, response, self._solution) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - def get(self, sid): + Returns: + tuple: (payload, status_code, headers) """ - Constructs a LogContext - :param sid: The SID that identifies the Log resource to fetch + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + 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 + def fetch(self) -> LogInstance: """ - return LogContext( + Fetch the LogInstance + + + :returns: The fetched LogInstance + """ + payload, _, _ = self._fetch() + 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a LogContext + Fetch the LogInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return LogContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -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. """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> LogInstance: """ - Initialize the LogPage + Asynchronous coroutine to fetch the LogInstance - :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 + :returns: The fetched LogInstance """ - super(LogPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = await self._fetch_async() + return LogInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of LogInstance + Asynchronous coroutine to fetch the LogInstance and return response metadata - :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 + :returns: ApiResponse with instance, status code, and headers """ - return LogInstance( + payload, status_code, headers = await self._fetch_async() + instance = 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"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str - """ - 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. """ - - def __init__(self, version, service_sid, environment_sid, sid): """ - Initialize the LogContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :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 - :returns: twilio.rest.serverless.v1.service.environment.log.LogContext - :rtype: twilio.rest.serverless.v1.service.environment.log.LogContext - """ - super(LogContext, self).__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) +class LogPage(Page): - def fetch(self): + def get_instance(self, payload: Dict[str, Any]) -> LogInstance: """ - Fetch the LogInstance + Build an instance of LogInstance - :returns: The fetched LogInstance - :rtype: twilio.rest.serverless.v1.service.environment.log.LogInstance + :param payload: Payload response from the API """ - payload = self._version.fetch(method='GET', uri=self._uri, ) return LogInstance( 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): + def __repr__(self) -> str: """ Provide a 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 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. """ - - class Level(object): - INFO = "info" - WARN = "warn" - ERROR = "error" - - 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'), - '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'), - } - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'environment_sid': environment_sid, - 'sid': sid or self._properties['sid'], - } +class LogList(ListResource): - @property - def _proxy(self): + def __init__(self, version: Version, service_sid: str, environment_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 LogList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Log resource from. + :param environment_sid: The SID of the environment with the Log resources to read. - :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'], + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + } + self._uri = ( + "/Services/{service_sid}/Environments/{environment_sid}/Logs".format( + **self._solution ) - return self._context + ) - @property - def sid(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]: """ - :returns: The unique string that identifies the Log resource - :rtype: unicode - """ - return self._properties['sid'] + 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. - @property - def account_sid(self): + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The SID of the Account that created the Log resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = self.page( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[LogInstance]: """ - return self._properties['account_sid'] + 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. - @property - def service_sid(self): + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The SID of the Service that the Log resource is associated with - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: """ - return self._properties['service_sid'] + Streams LogInstance and returns headers from first page - @property - def environment_sid(self): + + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The SID of the environment in which the log occurred - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - return self._properties['environment_sid'] + Asynchronously streams LogInstance and returns headers from first page - @property - def deployment_sid(self): + + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The SID of the deployment that corresponds to the log - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - return self._properties['deployment_sid'] + 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 function_sid(self): + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LogInstance]: """ - :returns: The SID of the function whose invocation produced the log - :rtype: unicode + Asynchronously lists LogInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['function_sid'] + Lists LogInstance and returns headers from first page - @property - def request_sid(self): + + :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: ApiResponse with list of instances, status code, and headers """ - :returns: The SID of the request associated with the log - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists LogInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['request_sid'] + Retrieve a single page of LogInstance records from the API. + Request is executed immediately - @property - def level(self): + :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 """ - :returns: The log level - :rtype: LogInstance.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, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LogPage(self._version, response, solution=self._solution) + + async def page_async( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LogPage: + """ + Asynchronously retrieve a single page of LogInstance records from the API. + Request is executed immediately + + :param function_sid: The SID of the function whose invocation produced the Log resources to read. + :param start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LogInstance """ - 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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with LogPage, status code, and headers + """ + data = values.of( + { + "FunctionSid": function_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = LogPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with LogPage, status code, and headers + """ + data = values.of( + { + "FunctionSid": function_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = LogPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 8b9b32a780..13597a5419 100644 --- a/twilio/rest/serverless/v1/service/environment/variable.py +++ b/twilio/rest/serverless/v1/service/environment/variable.py @@ -1,472 +1,1153 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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") - def __init__(self, version, service_sid, environment_sid): + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid or self.sid, + } + + self._context: Optional[VariableContext] = None + + @property + def _proxy(self) -> "VariableContext": """ - 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 + + :returns: VariableContext for this VariableInstance + """ + if self._context is None: + self._context = VariableContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the VariableInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the VariableInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the VariableInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the VariableInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "VariableInstance": + """ + Fetch the VariableInstance + + + :returns: The fetched VariableInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "VariableInstance": + """ + Asynchronous coroutine to fetch the VariableInstance + + + :returns: The fetched VariableInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VariableInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VariableInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> "VariableInstance": + """ + Update the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The updated VariableInstance + """ + return self._proxy.update( + key=key, + value=value, + ) + + async def update_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> "VariableInstance": + """ + Asynchronous coroutine to update the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The updated VariableInstance + """ + return await self._proxy.update_async( + key=key, + value=value, + ) + + def update_with_http_info( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the VariableInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + key=key, + value=value, + ) + + async def update_with_http_info_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the VariableInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + key=key, + value=value, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class VariableContext(InstanceContext): - :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 + def __init__( + self, version: Version, service_sid: str, environment_sid: str, sid: str + ): + """ + Initialize the VariableContext - :returns: twilio.rest.serverless.v1.service.environment.variable.VariableList - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableList + :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(VariableList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'service_sid': service_sid, 'environment_sid': environment_sid, } - self._uri = '/Services/{service_sid}/Environments/{environment_sid}/Variables'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Environments/{environment_sid}/Variables/{sid}".format( + **self._solution + ) - def stream(self, limit=None, page_size=None): + def _delete(self) -> tuple: """ - 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. + Internal helper for delete operation - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.serverless.v1.service.environment.variable.VariableInstance] + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the VariableInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success - def list(self, limit=None, page_size=None): + def delete_with_http_info(self) -> ApiResponse: """ - Lists VariableInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the VariableInstance and return response metadata - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Retrieve a single page of VariableInstance 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 + headers = values.of({}) - :returns: Page of VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariablePage + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Asynchronous coroutine that deletes the VariableInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return VariablePage(self._version, response, self._solution) + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success - def get_page(self, target_url): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Retrieve a specific page of VariableInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the VariableInstance and return response metadata - :param str target_url: API-generated URL for the requested results page - :returns: Page of VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariablePage + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) - return VariablePage(self._version, response, self._solution) + def fetch(self) -> VariableInstance: + """ + Fetch the VariableInstance + - def create(self, key, value): + :returns: The fetched VariableInstance """ - Create the VariableInstance + payload, _, _ = self._fetch() + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VariableInstance and return response metadata - :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 - :returns: The created VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> VariableInstance: """ - data = values.of({'Key': key, 'Value': value, }) + Asynchronous coroutine to fetch the VariableInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :returns: The fetched VariableInstance + """ + payload, _, _ = await self._fetch_async() 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_with_http_info_async(self) -> ApiResponse: """ - Constructs a VariableContext + Asynchronous coroutine to fetch the VariableInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return VariableContext( + payload, status_code, headers = await self._fetch_async() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __call__(self, sid): + def _update( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> tuple: """ - Constructs a VariableContext + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({}) - :param sid: The SID of the Variable resource to fetch + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: twilio.rest.serverless.v1.service.environment.variable.VariableContext - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableContext + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> VariableInstance: """ - return VariableContext( + Update the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The updated VariableInstance + """ + payload, _, _ = self._update(key=key, value=value) + 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): + def update_with_http_info( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Provide a friendly representation + Update the VariableInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return '' + payload, status_code, headers = self._update(key=key, value=value) + instance = VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + async def _update_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation -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. """ + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({}) - def __init__(self, version, response, solution): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> VariableInstance: """ - Initialize the VariablePage + Asynchronous coroutine to update the VariableInstance - :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 + :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.VariablePage - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariablePage + :returns: The updated VariableInstance """ - super(VariablePage, self).__init__(version, response) + payload, _, _ = await self._update_async(key=key, value=value) + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) - # Path Solution - self._solution = solution + async def update_with_http_info_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the VariableInstance and return response metadata + + :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_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of VariableInstance + payload, status_code, headers = await self._update_async(key=key, value=value) + instance = VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.serverless.v1.service.environment.variable.VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance + :returns: Machine friendly representation """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class VariablePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> VariableInstance: + """ + Build an instance of VariableInstance + + :param payload: Payload response from the API + """ + return VariableInstance( self._version, payload, - service_sid=self._solution['service_sid'], - environment_sid=self._solution['environment_sid'], + 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) -> tuple: """ - Fetch the VariableInstance + Internal helper for create operation - :returns: The fetched VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, key: str, value: str) -> VariableInstance: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Create the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + :returns: The created VariableInstance + """ + payload, _, _ = self._create(key=key, value=value) 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): + def create_with_http_info(self, key: str, value: str) -> ApiResponse: """ - Update the VariableInstance + Create the VariableInstance and return response metadata - :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(key=key, value=value) + instance = VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, key: str, value: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - 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" + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, key: str, value: str) -> VariableInstance: + """ + Asynchronously create the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The created VariableInstance + """ + payload, _, _ = await self._create_async(key=key, value=value) 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): + async def create_with_http_info_async(self, key: str, value: str) -> ApiResponse: """ - Deletes the VariableInstance + Asynchronously create the VariableInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._create_async(key=key, value=value) + instance = VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[VariableInstance]: """ - Provide a friendly representation + 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: 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 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'), - } + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[VariableInstance]: + """ + Asynchronously streams VariableInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'environment_sid': environment_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 = await self.page_async(page_size=limits["page_size"]) - :returns: VariableContext for this VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableContext + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - 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 + Streams VariableInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The unique string that identifies the Variable resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['sid'] + Asynchronously streams VariableInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The SID of the Account that created the Variable resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VariableInstance]: """ - return self._properties['account_sid'] + 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 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 Service that the Variable resource is associated with - :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[VariableInstance]: """ - return self._properties['service_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 environment_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 environment in which the variable exists - :rtype: unicode + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['environment_sid'] + Lists VariableInstance and returns headers from first page - @property - def key(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: ApiResponse with list of instances, status code, and headers """ - :returns: A string by which the Variable resource can be referenced - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['key'] + Asynchronously lists VariableInstance and returns headers from first page - @property - def value(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: ApiResponse with list of instances, status code, and headers """ - :returns: A string that contains the actual value of the variable - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['value'] + Retrieve a single page of VariableInstance 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 VariableInstance """ - :returns: The ISO 8601 date and time in GMT when the Variable 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 VariablePage(self._version, response, solution=self._solution) + + async def 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_created'] + Asynchronously retrieve a single page of VariableInstance 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 VariableInstance """ - :returns: The ISO 8601 date and time in GMT when the Variable 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 VariablePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Retrieve a single page with response metadata - @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: ApiResponse with VariablePage, status code, and headers """ - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = VariablePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['url'] + Asynchronously retrieve a single page with response metadata - 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: ApiResponse with VariablePage, status code, and headers """ - Fetch the VariableInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: The fetched VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = VariablePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> VariablePage: """ - return self._proxy.fetch() + Retrieve a specific page of VariableInstance records from the API. + Request is executed immediately - def update(self, key=values.unset, value=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of VariableInstance """ - Update the VariableInstance + response = self._version.domain.twilio.request("GET", target_url) + return VariablePage(self._version, response, solution=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 + async def get_page_async(self, target_url: str) -> VariablePage: + """ + Asynchronously retrieve a specific page of VariableInstance records from the API. + Request is executed immediately - :returns: The updated VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of VariableInstance """ - return self._proxy.update(key=key, value=value, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return VariablePage(self._version, response, solution=self._solution) - def delete(self): + def get(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 __call__(self, sid: str) -> VariableContext: + """ + Constructs a VariableContext + + :param sid: The SID of the Variable resource to update. + """ + return VariableContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 513be3f80e..31c142d1f8 100644 --- a/twilio/rest/serverless/v1/service/function/__init__.py +++ b/twilio/rest/serverless/v1/service/function/__init__.py @@ -1,460 +1,1076 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +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") - def __init__(self, version, service_sid): + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[FunctionContext] = None + + @property + def _proxy(self) -> "FunctionContext": """ - Initialize the FunctionList + 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 resource is associated with + :returns: FunctionContext for this FunctionInstance + """ + if self._context is None: + self._context = FunctionContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.serverless.v1.service.function.FunctionList - :rtype: twilio.rest.serverless.v1.service.function.FunctionList + def delete(self) -> bool: """ - super(FunctionList, self).__init__(version) + Deletes the FunctionInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Functions'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + 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 FunctionInstance - :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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FunctionInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists FunctionInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FunctionInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.serverless.v1.service.function.FunctionInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_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, }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "FunctionInstance": + """ + Asynchronous coroutine to fetch the FunctionInstance - return FunctionPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched FunctionInstance """ - Retrieve a specific page of FunctionInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FunctionInstance with HTTP info - :returns: Page of FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() - return FunctionPage(self._version, response, self._solution) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FunctionInstance with HTTP info - def create(self, friendly_name): + + :returns: ApiResponse with instance, status code, and headers """ - Create the FunctionInstance + return await self._proxy.fetch_with_http_info_async() - :param unicode friendly_name: A string to describe the Function resource + def update(self, friendly_name: str) -> "FunctionInstance": + """ + Update the FunctionInstance - :returns: The created FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The updated FunctionInstance """ - data = values.of({'FriendlyName': friendly_name, }) + return self._proxy.update( + friendly_name=friendly_name, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def update_async(self, friendly_name: str) -> "FunctionInstance": + """ + Asynchronous coroutine to update the FunctionInstance - return FunctionInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. - def get(self, sid): + :returns: The updated FunctionInstance """ - Constructs a FunctionContext + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - :param sid: The SID of the Function resource to fetch + def update_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Update the FunctionInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers """ - return FunctionContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: """ - Constructs a FunctionContext + Asynchronous coroutine to update the FunctionInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return FunctionContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) - def __repr__(self): + @property + def function_versions(self) -> FunctionVersionList: + """ + Access the function_versions + """ + return self._proxy.function_versions + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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) + + self._function_versions: Optional[FunctionVersionList] = None - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of FunctionInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.serverless.v1.service.function.FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance + def delete(self) -> bool: """ - return FunctionInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the FunctionInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the FunctionInstance and return response metadata -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. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the FunctionContext + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :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 + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.serverless.v1.service.function.FunctionContext - :rtype: twilio.rest.serverless.v1.service.function.FunctionContext + async def delete_async(self) -> bool: """ - super(FunctionContext, self).__init__(version) + Asynchronous coroutine that deletes the FunctionInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Functions/{sid}'.format(**self._solution) - # Dependents - self._function_versions = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FunctionInstance and return response metadata + - def fetch(self): + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> FunctionInstance: """ Fetch the FunctionInstance + :returns: The fetched FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FunctionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + async def fetch_async(self) -> FunctionInstance: + """ + Asynchronous coroutine to fetch the FunctionInstance + + + :returns: The fetched FunctionInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the FunctionInstance + Asynchronous coroutine to fetch the FunctionInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def update(self, friendly_name): + def _update(self, friendly_name: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, friendly_name: str) -> 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 updated FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance """ - data = values.of({'FriendlyName': friendly_name, }) + payload, _, _ = self._update(friendly_name=friendly_name) + return FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def update_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Update the FunctionInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for update operation + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async(self, friendly_name: str) -> FunctionInstance: + """ + Asynchronous coroutine to update the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The updated FunctionInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) 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"], + ) + + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronous coroutine to update the FunctionInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 get_instance(self, payload: Dict[str, Any]) -> FunctionInstance: + """ + Build an instance of FunctionInstance - def __init__(self, version, payload, service_sid, sid=None): + :param payload: Payload response from the API """ - Initialize the FunctionInstance - :returns: twilio.rest.serverless.v1.service.function.FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance + return FunctionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: """ - super(FunctionInstance, 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'), - '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 "" + + +class FunctionList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the FunctionList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Function resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/Functions".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create(self, friendly_name: str) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: FunctionContext for this FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, friendly_name: str) -> FunctionInstance: """ - if self._context is None: - self._context = FunctionContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the FunctionInstance - @property - def 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 unique string that identifies the Function resource - :rtype: unicode + payload, _, _ = self._create(friendly_name=friendly_name) + return FunctionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info(self, friendly_name: str) -> ApiResponse: """ - return self._properties['sid'] + Create the FunctionInstance and return response metadata - @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: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Account that created the Function resource - :rtype: unicode + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = FunctionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, friendly_name: str) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for create operation - @property - def service_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, friendly_name: str) -> FunctionInstance: """ - return self._properties['service_sid'] + Asynchronously create the FunctionInstance - @property - def friendly_name(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 string that you assigned to describe the Function resource - :rtype: unicode + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return FunctionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: """ - return self._properties['friendly_name'] + Asynchronously create the FunctionInstance and return response metadata - @property - def date_created(self): + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The ISO 8601 date and time in GMT when the Function resource was created - :rtype: datetime + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = FunctionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FunctionInstance]: """ - return self._properties['date_created'] + 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_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 Function 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[FunctionInstance]: """ - return self._properties['date_updated'] + 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 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 Function 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['url'] + Streams FunctionInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The URLs of nested resources of the function - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['links'] + Asynchronously streams FunctionInstance and returns headers from first 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 fetch(self): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Fetch the FunctionInstance + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :returns: The fetched FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FunctionInstance]: """ - return self._proxy.fetch() + Lists FunctionInstance 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 """ - Deletes the FunctionInstance - :returns: True if delete succeeds, False otherwise - :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[FunctionInstance]: """ - return self._proxy.delete() + Asynchronously lists FunctionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - def update(self, friendly_name): + :returns: list that will contain up to limit results """ - Update the FunctionInstance - :param unicode friendly_name: A string to describe the Function resource + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - :returns: The updated FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.update(friendly_name, ) + Lists FunctionInstance and returns headers from first page - @property - def function_versions(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: ApiResponse with list of instances, status code, and headers """ - Access the function_versions + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.function_versions + Asynchronously lists FunctionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FunctionPage: + """ + Retrieve a single page of FunctionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FunctionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FunctionPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FunctionPage: + """ + Asynchronously retrieve a single page of FunctionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FunctionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FunctionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FunctionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FunctionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FunctionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FunctionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> FunctionPage: + """ + Retrieve a specific page of FunctionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FunctionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FunctionPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> FunctionPage: + """ + Asynchronously retrieve a specific page of FunctionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FunctionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FunctionPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> FunctionContext: + """ + Constructs a FunctionContext + + :param sid: The SID of the Function resource to update. + """ + return FunctionContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> FunctionContext: + """ + Constructs a FunctionContext + + :param sid: The SID of the Function resource to update. + """ + return FunctionContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 6e5d78584e..75cdb11b4f 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,743 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +class FunctionVersionInstance(InstanceResource): - def __init__(self, version, service_sid, function_sid): - """ - Initialize the FunctionVersionList + 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 Function Version resource is associated with - :param function_sid: The SID of the function that is the parent of the function 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") - :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid or self.sid, + } + + self._context: Optional[FunctionVersionContext] = None + + @property + def _proxy(self) -> "FunctionVersionContext": """ - super(FunctionVersionList, 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, 'function_sid': function_sid, } - self._uri = '/Services/{service_sid}/Functions/{function_sid}/Versions'.format(**self._solution) + :returns: FunctionVersionContext for this FunctionVersionInstance + """ + if self._context is None: + self._context = FunctionVersionContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the FunctionVersionInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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 """ - 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) -> "FunctionVersionInstance": + """ + Asynchronous coroutine to fetch the FunctionVersionInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FunctionVersionInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.serverless.v1.service.function.function_version.FunctionVersionInstance] + + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch_with_http_info() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of FunctionVersionInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the FunctionVersionInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of FunctionVersionInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionPage + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_with_http_info_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + @property + def function_version_content(self) -> FunctionVersionContentList: + """ + Access the function_version_content + """ + return self._proxy.function_version_content - return FunctionVersionPage(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 FunctionVersionInstance 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 FunctionVersionInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionPage +class FunctionVersionContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, function_sid: str, sid: str): """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Initialize the FunctionVersionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Function Version resource from. + :param function_sid: The SID of the function that is the parent of the Function Version resource to fetch. + :param sid: The SID of the Function Version resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Functions/{function_sid}/Versions/{sid}".format( + **self._solution + ) ) - return FunctionVersionPage(self._version, response, self._solution) + self._function_version_content: Optional[FunctionVersionContentList] = None - def get(self, sid): + def _fetch(self) -> tuple: """ - Constructs a FunctionVersionContext + Internal helper for fetch operation - :param sid: The SID that identifies the Function Version resource to fetch + Returns: + tuple: (payload, status_code, headers) + """ - :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> FunctionVersionInstance: """ - return FunctionVersionContext( + Fetch the FunctionVersionInstance + + + :returns: The fetched FunctionVersionInstance + """ + payload, _, _ = self._fetch() + 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a FunctionVersionContext + Fetch the FunctionVersionInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return FunctionVersionContext( + payload, status_code, headers = self._fetch() + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -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. """ + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + async def fetch_async(self) -> FunctionVersionInstance: """ - Initialize the FunctionVersionPage + Asynchronous coroutine to fetch the FunctionVersionInstance - :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 + :returns: The fetched FunctionVersionInstance """ - super(FunctionVersionPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = await self._fetch_async() + return FunctionVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of FunctionVersionInstance + Asynchronous coroutine to fetch the FunctionVersionInstance and return response metadata - :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 + :returns: ApiResponse with instance, status code, and headers """ - return FunctionVersionInstance( + payload, status_code, headers = await self._fetch_async() + instance = 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"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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): + 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 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 FunctionVersionPage(Page): - def __init__(self, version, service_sid, function_sid, sid): + def get_instance(self, payload: Dict[str, Any]) -> FunctionVersionInstance: """ - Initialize the FunctionVersionContext + Build an instance of FunctionVersionInstance + + :param payload: Payload response from the API + """ + + return FunctionVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + ) - :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 + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext + :returns: Machine friendly representation """ - super(FunctionVersionContext, self).__init__(version) + return "" - # 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 +class FunctionVersionList(ListResource): - def fetch(self): + def __init__(self, version: Version, service_sid: str, function_sid: str): """ - Fetch the FunctionVersionInstance + Initialize the FunctionVersionList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Function Version resources from. + :param function_sid: The SID of the function that is the parent of the Function Version resources to read. - :returns: The fetched FunctionVersionInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + super().__init__(version) - return FunctionVersionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - function_sid=self._solution['function_sid'], - sid=self._solution['sid'], + # Path Solution + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + } + self._uri = "/Services/{service_sid}/Functions/{function_sid}/Versions".format( + **self._solution ) - @property - def function_version_content(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FunctionVersionInstance]: """ - Access the function_version_content + 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: 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 limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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._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 = self.page(page_size=limits["page_size"]) - def __repr__(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FunctionVersionInstance]: """ - Provide a friendly representation + 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. - :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 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. """ + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams FunctionVersionInstance and returns headers from first page - class Visibility(object): - PUBLIC = "public" - PRIVATE = "private" - PROTECTED = "protected" - def __init__(self, version, payload, service_sid, function_sid, sid=None): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Initialize the FunctionVersionInstance + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionInstance + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(FunctionVersionInstance, self).__init__(version) + Asynchronously streams FunctionVersionInstance and returns headers from first page - # 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'), - } - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'function_sid': function_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: tuple of (generator, status_code, headers) where generator yields instances """ - 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_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - :returns: FunctionVersionContext for this FunctionVersionInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[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'], + Lists FunctionVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FunctionVersionInstance]: """ - :returns: The unique string that identifies the Function Version resource - :rtype: unicode + Asynchronously lists FunctionVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['sid'] - @property - def account_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Account that created the Function Version resource - :rtype: unicode + Lists FunctionVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['account_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def service_sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Service that the Function Version resource is associated with - :rtype: unicode + Asynchronously lists FunctionVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['service_sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def function_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, + ) -> FunctionVersionPage: """ - :returns: The SID of the function that is the parent of the function version - :rtype: unicode + Retrieve a single page of FunctionVersionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FunctionVersionInstance """ - return self._properties['function_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def path(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 FunctionVersionPage(self._version, response, solution=self._solution) + + async def 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: """ - :returns: The URL-friendly string by which the function version can be referenced - :rtype: unicode + Asynchronously retrieve a single page of FunctionVersionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FunctionVersionInstance """ - 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 FunctionVersionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The access control that determines how the function version can be accessed - :rtype: FunctionVersionInstance.Visibility + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FunctionVersionPage, status code, and headers """ - return self._properties['visibility'] + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FunctionVersionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The ISO 8601 date and time in GMT when the Function Version resource was created - :rtype: datetime + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FunctionVersionPage, status code, and headers """ - return self._properties['date_created'] + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FunctionVersionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> FunctionVersionPage: """ - :returns: The absolute URL of the Function Version resource - :rtype: unicode + 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['url'] + response = self._version.domain.twilio.request("GET", target_url) + return FunctionVersionPage(self._version, response, solution=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, solution=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..a253ad6ca9 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,306 @@ -# 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.api_response import ApiResponse 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 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. """ - - def __init__(self, version, service_sid, function_sid, sid): - """ - Initialize the FunctionVersionContentList +from twilio.base.version import Version - :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: 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 - """ - super(FunctionVersionContentList, self).__init__(version) +class FunctionVersionContentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Function Version resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Function Version resource. + :ivar service_sid: The SID of the Service that the Function Version resource is associated with. + :ivar function_sid: The SID of the Function that is the parent of the Function Version. + :ivar content: The content of the Function Version resource. + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + function_sid: str, + sid: str, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.function_sid: Optional[str] = payload.get("function_sid") + self.content: Optional[str] = payload.get("content") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid, + } - # Path Solution - self._solution = {'service_sid': service_sid, 'function_sid': function_sid, 'sid': sid, } + self._context: Optional[FunctionVersionContentContext] = None - def get(self): + @property + def _proxy(self) -> "FunctionVersionContentContext": """ - Constructs a FunctionVersionContentContext + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: 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: FunctionVersionContentContext for this FunctionVersionContentInstance """ - return FunctionVersionContentContext( - self._version, - service_sid=self._solution['service_sid'], - function_sid=self._solution['function_sid'], - sid=self._solution['sid'], - ) + if self._context is None: + self._context = FunctionVersionContentContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + return self._context - def __call__(self): + def fetch(self) -> "FunctionVersionContentInstance": """ - Constructs a FunctionVersionContentContext + Fetch the FunctionVersionContentInstance - :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 - """ - return FunctionVersionContentContext( - self._version, - service_sid=self._solution['service_sid'], - function_sid=self._solution['function_sid'], - sid=self._solution['sid'], - ) - def __repr__(self): + :returns: The fetched FunctionVersionContentInstance """ - Provide a friendly representation + return self._proxy.fetch() - :returns: Machine friendly representation - :rtype: str + async def fetch_async(self) -> "FunctionVersionContentInstance": """ - return '' + Asynchronous coroutine to fetch the FunctionVersionContentInstance -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. """ + :returns: The fetched FunctionVersionContentInstance + """ + return await self._proxy.fetch_async() - def __init__(self, version, response, solution): + def fetch_with_http_info(self) -> ApiResponse: """ - Initialize the FunctionVersionContentPage + Fetch the FunctionVersionContentInstance with HTTP info - :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 - :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 + :returns: ApiResponse with instance, status code, and headers """ - super(FunctionVersionContentPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info() - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of FunctionVersionContentInstance + Asynchronous coroutine to fetch the FunctionVersionContentInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return FunctionVersionContentInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - function_sid=self._solution['function_sid'], - sid=self._solution['sid'], - ) + return await self._proxy.fetch_with_http_info_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 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. """ - def __init__(self, version, service_sid, function_sid, sid): + def __init__(self, version: Version, service_sid: str, function_sid: str, sid: str): """ Initialize the FunctionVersionContentContext - :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 + :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(FunctionVersionContentContext, 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}/Content'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Functions/{function_sid}/Versions/{sid}/Content".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - def fetch(self): + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> FunctionVersionContentInstance: """ Fetch the FunctionVersionContentInstance + :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, _, _ = self._fetch() 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): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + def fetch_with_http_info(self) -> ApiResponse: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Fetch the FunctionVersionContentInstance and return response metadata -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. """ + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FunctionVersionContentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __init__(self, version, payload, service_sid, function_sid, sid): + async def _fetch_async(self) -> tuple: """ - Initialize the FunctionVersionContentInstance + Internal async helper for fetch operation - :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: + tuple: (payload, status_code, headers) """ - 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'), - } + headers = values.of({}) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'function_sid': function_sid, 'sid': 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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: FunctionVersionContentContext for this FunctionVersionContentInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentContext + async def fetch_async(self) -> 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 + Asynchronous coroutine to fetch the FunctionVersionContentInstance - @property - def sid(self): - """ - :returns: The unique string that identifies the Function Version resource - :rtype: unicode - """ - return self._properties['sid'] - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the Function Version resource - :rtype: unicode + :returns: The fetched FunctionVersionContentInstance """ - return self._properties['account_sid'] + payload, _, _ = await self._fetch_async() + return FunctionVersionContentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) - @property - def service_sid(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: The SID of the Service that the Function Version resource is associated with - :rtype: unicode + Asynchronous coroutine to fetch the FunctionVersionContentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['service_sid'] + payload, status_code, headers = await self._fetch_async() + instance = FunctionVersionContentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def function_sid(self): + def __repr__(self) -> str: """ - :returns: The SID of the Function that is the parent of the Function Version - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['function_sid'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def content(self): + +class FunctionVersionContentList(ListResource): + + def __init__(self, version: Version, service_sid: str, function_sid: str, sid: str): """ - :returns: The content of the Function Version resource - :rtype: unicode + Initialize the FunctionVersionContentList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Function Version content from. + :param function_sid: The SID of the Function that is the parent of the Function Version content to fetch. + :param sid: The SID of the Function Version content to fetch. + """ - return self._properties['content'] + super().__init__(version) - @property - def url(self): + # Path Solution + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid, + } + + def get(self) -> FunctionVersionContentContext: """ - :returns: The url - :rtype: unicode + Constructs a FunctionVersionContentContext + """ - 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 2f58c078be..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_valid(self): - """ - :rtype: twilio.rest.studio.v2.flow_validate.FlowValidateList - """ - return self.v2.flow_valid - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' + def flow_validate(self) -> FlowValidateList: + warn( + "flow_validate is deprecated. Use v2.flow_validate instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.flow_validate diff --git a/twilio/rest/studio/v1/__init__.py b/twilio/rest/studio/v1/__init__.py index 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 6d1050164c..a2795280f7 100644 --- a/twilio/rest/studio/v1/flow/__init__.py +++ b/twilio/rest/studio/v1/flow/__init__.py @@ -1,427 +1,814 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): - """ """ +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 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") - :returns: twilio.rest.studio.v1.flow.FlowList - :rtype: twilio.rest.studio.v1.flow.FlowList - """ - super(FlowList, self).__init__(version) + self._solution = { + "sid": sid or self.sid, + } - # Path Solution - self._solution = {} - self._uri = '/Flows'.format(**self._solution) + 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. + 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: FlowContext for this FlowInstance + """ + if self._context is None: + self._context = FlowContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v1.flow.FlowInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the FlowInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists 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 that 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 await self._proxy.delete_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of FlowInstance records from the API. - Request is executed immediately + Deletes the FlowInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with success boolean, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.delete_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlowInstance with HTTP info - return FlowPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with success boolean, status code, and headers """ - Retrieve a specific page of FlowInstance records from the API. - Request is executed immediately + return await self._proxy.delete_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def fetch(self) -> "FlowInstance": + """ + Fetch the FlowInstance - :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 self._proxy.fetch() - return FlowPage(self._version, response, self._solution) + async def fetch_async(self) -> "FlowInstance": + """ + Asynchronous coroutine to fetch the FlowInstance - def get(self, sid): + + :returns: The fetched FlowInstance """ - Constructs a FlowContext + return await self._proxy.fetch_async() - :param sid: The SID that identifies the resource to fetch + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowInstance with HTTP info - :returns: twilio.rest.studio.v1.flow.FlowContext - :rtype: twilio.rest.studio.v1.flow.FlowContext + + :returns: ApiResponse with instance, status code, and headers """ - return FlowContext(self._version, sid=sid, ) + return self._proxy.fetch_with_http_info() - def __call__(self, sid): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Constructs a FlowContext + Asynchronous coroutine to fetch the FlowInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return FlowContext(self._version, sid=sid, ) + return await self._proxy.fetch_with_http_info_async() - def __repr__(self): + @property + def engagements(self) -> EngagementList: + """ + Access the engagements + """ + return self._proxy.engagements + + @property + def executions(self) -> ExecutionList: + """ + Access the executions + """ + return self._proxy.executions + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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 + self._solution = { + "sid": sid, + } + self._uri = "/Flows/{sid}".format(**self._solution) + + self._engagements: Optional[EngagementList] = None + self._executions: Optional[ExecutionList] = None - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of FlowInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: twilio.rest.studio.v1.flow.FlowInstance - :rtype: twilio.rest.studio.v1.flow.FlowInstance + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return FlowInstance(self._version, payload, ) + Deletes the FlowInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the FlowInstance and return response metadata -class FlowContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the FlowContext - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch + headers = values.of({}) - :returns: twilio.rest.studio.v1.flow.FlowContext - :rtype: twilio.rest.studio.v1.flow.FlowContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(FlowContext, self).__init__(version) + Asynchronous coroutine that deletes the FlowInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Flows/{sid}'.format(**self._solution) - # Dependents - self._engagements = None - self._executions = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success - def fetch(self): + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlowInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + 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, ) + payload, _, _ = self._fetch() + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowInstance and return response metadata - return FlowInstance(self._version, payload, sid=self._solution['sid'], ) - def delete(self): + :returns: ApiResponse with instance, status code, and headers """ - Deletes the FlowInstance + payload, status_code, headers = self._fetch() + instance = FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> FlowInstance: + """ + Asynchronous coroutine to fetch the FlowInstance + + + :returns: The fetched FlowInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, _, _ = await self._fetch_async() + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 - :returns: twilio.rest.studio.v1.flow.FlowInstance - :rtype: twilio.rest.studio.v1.flow.FlowInstance + return FlowInstance(self._version, payload) + + 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): +class FlowList(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 FlowList + + :param version: Version that contains the resource - :returns: FlowContext for this FlowInstance - :rtype: twilio.rest.studio.v1.flow.FlowContext """ - if self._context is None: - self._context = FlowContext(self._version, sid=self._solution['sid'], ) - return self._context + super().__init__(version) - @property - def sid(self): + self._uri = "/Flows" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FlowInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Streams FlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FlowInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Asynchronously streams FlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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 friendly_name(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The string that you assigned to describe the Flow - :rtype: unicode + Streams FlowInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def status(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The status of the Flow - :rtype: FlowInstance.Status + Asynchronously streams FlowInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['status'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def version(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowInstance]: """ - :returns: The latest version number of the Flow's definition - :rtype: unicode + Lists FlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['version'] - @property - def date_created(self): + return 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]: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Asynchronously lists FlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['date_created'] - @property - def date_updated(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Lists FlowInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_updated'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def url(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The absolute URL of the resource - :rtype: unicode + Asynchronously lists FlowInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['url'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> FlowPage: """ - :returns: Nested resource URLs - :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['links'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return 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.v1.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" - def delete(self): + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlowPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the FlowInstance + Retrieve a single page with response metadata - :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: ApiResponse with FlowPage, status code, and headers """ - return self._proxy.delete() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def engagements(self): + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FlowPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Access the engagements + Asynchronously retrieve a single page with response metadata + - :returns: twilio.rest.studio.v1.flow.engagement.EngagementList - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementList + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FlowPage, status code, and headers """ - return self._proxy.engagements + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def executions(self): + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FlowPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> FlowPage: """ - Access the executions + 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.v1.flow.execution.ExecutionList - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionList + :returns: Page of FlowInstance """ - return self._proxy.executions + response = self._version.domain.twilio.request("GET", target_url) + return FlowPage(self._version, response) + + async def get_page_async(self, target_url: str) -> FlowPage: + """ + Asynchronously retrieve a specific page of FlowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlowInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FlowPage(self._version, response) + + def get(self, sid: str) -> FlowContext: + """ + Constructs a FlowContext + + :param sid: The SID of the Flow resource to fetch. + """ + return FlowContext(self._version, sid=sid) + + def __call__(self, sid: str) -> FlowContext: + """ + Constructs a FlowContext + + :param sid: The SID of the Flow resource to fetch. + """ + return FlowContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 f837830cc6..a899206caf 100644 --- a/twilio/rest/studio/v1/flow/engagement/__init__.py +++ b/twilio/rest/studio/v1/flow/engagement/__init__.py @@ -1,483 +1,977 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): - """ """ +class EngagementInstance(InstanceResource): - def __init__(self, version, flow_sid): - """ - Initialize the EngagementList + class Status(object): + ACTIVE = "active" + ENDED = "ended" - :param Version version: Version that contains the resource - :param flow_sid: The SID of the Flow + """ + :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") - :returns: twilio.rest.studio.v1.flow.engagement.EngagementList - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementList - """ - super(EngagementList, self).__init__(version) + self._solution = { + "flow_sid": flow_sid, + "sid": sid or self.sid, + } - # Path Solution - self._solution = {'flow_sid': flow_sid, } - self._uri = '/Flows/{flow_sid}/Engagements'.format(**self._solution) + 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. + 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: EngagementContext for this EngagementInstance + """ + if self._context is None: + self._context = EngagementContext( + self._version, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v1.flow.engagement.EngagementInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the EngagementInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists EngagementInstance 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 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 await self._proxy.delete_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of EngagementInstance records from the API. - Request is executed immediately + Deletes the EngagementInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with success boolean, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.delete_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EngagementInstance with HTTP info - return EngagementPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with success boolean, status code, and headers """ - Retrieve a specific page of EngagementInstance records from the API. - Request is executed immediately + return await self._proxy.delete_with_http_info_async() - :param str target_url: API-generated URL for the requested results page - - :returns: Page of EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementPage + def fetch(self) -> "EngagementInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Fetch the EngagementInstance - return EngagementPage(self._version, response, self._solution) - def create(self, to, from_, parameters=values.unset): + :returns: The fetched EngagementInstance """ - Create 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 + return self._proxy.fetch() - :returns: The created EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance + async def fetch_async(self) -> "EngagementInstance": """ - data = values.of({'To': to, 'From': from_, 'Parameters': serialize.object(parameters), }) + Asynchronous coroutine to fetch the EngagementInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return EngagementInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) + :returns: The fetched EngagementInstance + """ + return await self._proxy.fetch_async() - def get(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a EngagementContext + Fetch the EngagementInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return EngagementContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, ) + return self._proxy.fetch_with_http_info() - def __call__(self, sid): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Constructs a EngagementContext + Asynchronous coroutine to fetch the EngagementInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return EngagementContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, ) + return await self._proxy.fetch_with_http_info_async() - def __repr__(self): + @property + def engagement_context(self) -> EngagementContextList: + """ + Access the engagement_context + """ + return self._proxy.engagement_context + + @property + def steps(self) -> StepList: + """ + Access the steps + """ + return self._proxy.steps + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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 + self._solution = { + "flow_sid": flow_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{sid}".format(**self._solution) + + self._engagement_context: Optional[EngagementContextList] = None + self._steps: Optional[StepList] = None - def get_instance(self, payload): + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of EngagementInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.studio.v1.flow.engagement.EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return EngagementInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) + Deletes the EngagementInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the EngagementInstance and return response metadata -class EngagementContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, flow_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the EngagementContext + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param Version version: Version that contains the resource - :param flow_sid: Flow SID - :param sid: The SID of the Engagement resource to fetch + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.studio.v1.flow.engagement.EngagementContext - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext + async def delete_async(self) -> bool: """ - super(EngagementContext, self).__init__(version) + Asynchronous coroutine that deletes the EngagementInstance - # Path Solution - self._solution = {'flow_sid': flow_sid, 'sid': sid, } - self._uri = '/Flows/{flow_sid}/Engagements/{sid}'.format(**self._solution) - # Dependents - self._steps = None - self._engagement_context = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EngagementInstance and return response metadata + - def fetch(self): + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + 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, ) - + payload, _, _ = self._fetch() 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Deletes the EngagementInstance + Fetch the EngagementInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = self._fetch() + instance = EngagementInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def steps(self): + async def _fetch_async(self) -> tuple: """ - Access the steps + Internal async helper for fetch operation - :returns: twilio.rest.studio.v1.flow.engagement.step.StepList - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepList + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> EngagementInstance: + """ + Asynchronous coroutine to fetch the EngagementInstance + + + :returns: The fetched EngagementInstance + """ + payload, _, _ = await self._fetch_async() + return EngagementInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EngagementInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EngagementInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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: Machine friendly representation + """ + return "" + + +class EngagementList(ListResource): + + def __init__(self, version: Version, flow_sid: str): + """ + Initialize the EngagementList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow to read Engagements from. - :returns: twilio.rest.studio.v1.flow.engagement.EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance """ - super(EngagementInstance, self).__init__(version) + super().__init__(version) - # 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'), + # Path Solution + self._solution = { + "flow_sid": flow_sid, } + self._uri = "/Flows/{flow_sid}/Engagements".format(**self._solution) - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: EngagementContext for this EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> EngagementInstance: """ - if self._context is None: - self._context = EngagementContext( - self._version, - flow_sid=self._solution['flow_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the EngagementInstance - @property - def sid(self): + :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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = self._create(to=to, from_=from_, parameters=parameters) + return EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def create_with_http_info( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ApiResponse: """ - return self._properties['sid'] + Create the EngagementInstance and return response metadata - @property - def account_sid(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Account that created the resource - :rtype: unicode + payload, status_code, headers = self._create( + to=to, from_=from_, parameters=parameters + ) + instance = EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for create operation - @property - def flow_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the Flow - :rtype: unicode + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> EngagementInstance: """ - return self._properties['flow_sid'] + Asynchronously create the EngagementInstance - @property - def contact_sid(self): + :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 """ - :returns: The SID of the Contact - :rtype: unicode + payload, _, _ = await self._create_async( + to=to, from_=from_, parameters=parameters + ) + return EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + async def create_with_http_info_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ApiResponse: """ - return self._properties['contact_sid'] + Asynchronously create the EngagementInstance and return response metadata - @property - def contact_channel_address(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The phone number, SIP address or Client identifier that triggered this Engagement - :rtype: unicode + payload, status_code, headers = await self._create_async( + to=to, from_=from_, parameters=parameters + ) + instance = EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EngagementInstance]: """ - return self._properties['contact_channel_address'] + 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. - @property - def context(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 current state of the execution flow - :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[EngagementInstance]: """ - return self._properties['context'] + 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. - @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 Engagement - :rtype: EngagementInstance.Status + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['status'] + Streams EngagementInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The ISO 8601 date and time in GMT when the Engagement was created - :rtype: datetime + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_created'] + Asynchronously streams EngagementInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The ISO 8601 date and time in GMT when the Engagement was last updated - :rtype: datetime + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EngagementInstance]: """ - return self._properties['date_updated'] + Lists EngagementInstance 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 list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EngagementInstance]: """ - return self._properties['url'] + 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. - @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 the Engagement's nested resources - :rtype: unicode + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['links'] + Lists EngagementInstance and returns headers from first page - 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: ApiResponse with list of instances, status code, and headers """ - Fetch the EngagementInstance + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: The fetched EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.fetch() + Asynchronously lists EngagementInstance and returns headers from first page - 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: ApiResponse with list of instances, status code, and headers """ - Deletes the EngagementInstance + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + 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: """ - return self._proxy.delete() + Retrieve a single page of EngagementInstance records from the API. + Request is executed immediately - @property - def steps(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 EngagementInstance """ - Access the steps + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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, solution=self._solution) - :returns: twilio.rest.studio.v1.flow.engagement.step.StepList - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepList + async def 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: """ - return self._proxy.steps + Asynchronously retrieve a single page of EngagementInstance records from the API. + Request is executed immediately - @property - def engagement_context(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 EngagementInstance """ - Access the engagement_context + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EngagementPage(self._version, response, solution=self._solution) - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.engagement_context + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EngagementPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EngagementPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EngagementPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EngagementPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> EngagementPage: + """ + Retrieve a specific page of EngagementInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EngagementInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EngagementPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> EngagementPage: + """ + Asynchronously retrieve a specific page of EngagementInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EngagementInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EngagementPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> EngagementContext: + """ + Constructs a EngagementContext + + :param sid: The SID of the Engagement resource to fetch. + """ + return EngagementContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) + + def __call__(self, sid: str) -> EngagementContext: + """ + Constructs a EngagementContext + + :param sid: The SID of the Engagement resource to fetch. + """ + return EngagementContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..3b0cf3cf52 100644 --- a/twilio/rest/studio/v1/flow/engagement/engagement_context.py +++ b/twilio/rest/studio/v1/flow/engagement/engagement_context.py @@ -1,263 +1,289 @@ -# 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.api_response import ApiResponse 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 EngagementContextList(ListResource): - """ """ - - def __init__(self, version, flow_sid, engagement_sid): - """ - Initialize the EngagementContextList +from twilio.base.version import Version - :param Version version: Version that contains the resource - :param flow_sid: Flow SID - :param engagement_sid: Engagement SID - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList - """ - super(EngagementContextList, self).__init__(version) +class EngagementContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the Account. + :ivar context: As your flow executes, we save the state in what's called the Flow Context. Any data in the flow context can be accessed by your widgets as variables, either in configuration fields or in text areas as variable substitution. + :ivar engagement_sid: The SID of the Engagement. + :ivar flow_sid: The SID of the Flow. + :ivar url: The URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + engagement_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.engagement_sid: Optional[str] = payload.get("engagement_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + } - # Path Solution - self._solution = {'flow_sid': flow_sid, 'engagement_sid': engagement_sid, } + self._context: Optional[EngagementContextContext] = None - def get(self): + @property + def _proxy(self) -> "EngagementContextContext": """ - Constructs a EngagementContextContext + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext + :returns: EngagementContextContext for this EngagementContextInstance """ - return EngagementContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - ) + if self._context is None: + self._context = EngagementContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + return self._context - def __call__(self): + def fetch(self) -> "EngagementContextInstance": """ - Constructs a EngagementContextContext + Fetch the EngagementContextInstance - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext - """ - return EngagementContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - ) - def __repr__(self): + :returns: The fetched EngagementContextInstance """ - Provide a friendly representation + return self._proxy.fetch() - :returns: Machine friendly representation - :rtype: str + async def fetch_async(self) -> "EngagementContextInstance": """ - return '' + Asynchronous coroutine to fetch the EngagementContextInstance -class EngagementContextPage(Page): - """ """ + :returns: The fetched EngagementContextInstance + """ + return await self._proxy.fetch_async() - def __init__(self, version, response, solution): + def fetch_with_http_info(self) -> ApiResponse: """ - Initialize the EngagementContextPage + Fetch the EngagementContextInstance with HTTP info - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: Flow SID - :param engagement_sid: Engagement SID - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextPage - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextPage + :returns: ApiResponse with instance, status code, and headers """ - super(EngagementContextPage, self).__init__(version, response) + return self._proxy.fetch_with_http_info() - # Path Solution - self._solution = solution - - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of EngagementContextInstance + Asynchronous coroutine to fetch the EngagementContextInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return EngagementContextInstance( - self._version, - payload, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - ) + return await self._proxy.fetch_with_http_info_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 EngagementContextContext(InstanceContext): - """ """ - def __init__(self, version, flow_sid, engagement_sid): + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): """ Initialize the EngagementContextContext - :param Version version: Version that contains the resource - :param flow_sid: Flow SID - :param engagement_sid: Engagement SID - - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow. + :param engagement_sid: The SID of the Engagement. """ - super(EngagementContextContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'flow_sid': flow_sid, 'engagement_sid': engagement_sid, } - self._uri = '/Flows/{flow_sid}/Engagements/{engagement_sid}/Context'.format(**self._solution) + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{engagement_sid}/Context".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EngagementContextInstance: """ 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, _, _ = self._fetch() 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 + def fetch_with_http_info(self) -> ApiResponse: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Fetch the EngagementContextInstance and return response metadata -class EngagementContextInstance(InstanceResource): - """ """ + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EngagementContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __init__(self, version, payload, flow_sid, engagement_sid): + async def _fetch_async(self) -> tuple: """ - Initialize the EngagementContextInstance + Internal async helper for fetch operation - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextInstance + Returns: + tuple: (payload, status_code, headers) """ - 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'), - } + headers = values.of({}) - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'engagement_sid': engagement_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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: EngagementContextContext for this EngagementContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext + async def fetch_async(self) -> 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 + Asynchronous coroutine to fetch the EngagementContextInstance - @property - def account_sid(self): - """ - :returns: Account SID - :rtype: unicode + + :returns: The fetched EngagementContextInstance """ - return self._properties['account_sid'] + payload, _, _ = await self._fetch_async() + return EngagementContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) - @property - def context(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: Flow state - :rtype: dict + Asynchronous coroutine to fetch the EngagementContextInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['context'] + payload, status_code, headers = await self._fetch_async() + instance = EngagementContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def engagement_sid(self): + def __repr__(self) -> str: """ - :returns: Engagement SID - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['engagement_sid'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def flow_sid(self): + +class EngagementContextList(ListResource): + + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): """ - :returns: Flow SID - :rtype: unicode + Initialize the EngagementContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow. + :param engagement_sid: The SID of the Engagement. + """ - return self._properties['flow_sid'] + super().__init__(version) - @property - def url(self): + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + } + + def get(self) -> EngagementContextContext: """ - :returns: The URL of the resource - :rtype: unicode + Constructs a EngagementContextContext + """ - 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 7c394858ef..25a925f124 100644 --- a/twilio/rest/studio/v1/flow/engagement/step/__init__.py +++ b/twilio/rest/studio/v1/flow/engagement/step/__init__.py @@ -1,449 +1,743 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): - """ """ +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 type: The type of the widget that was executed. + :ivar date_created: 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.type: Optional[str] = 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.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") - def __init__(self, version, flow_sid, engagement_sid): - """ - Initialize the StepList + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "sid": sid or self.sid, + } - :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._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'], limits['page_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): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of StepInstance records from the API. - Request is executed immediately + Fetch the StepInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of StepInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepPage + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the StepInstance with HTTP info - return StepPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - 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 + return await self._proxy.fetch_with_http_info_async() - :returns: Page of StepInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepPage + @property + def step_context(self) -> StepContextList: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Access the step_context + """ + return self._proxy.step_context - return StepPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a StepContext + 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.v1.flow.engagement.step.StepContext - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepContext - """ - return StepContext( - self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - sid=sid, - ) +class StepContext(InstanceContext): - def __call__(self, sid): + def __init__(self, version: Version, flow_sid: str, engagement_sid: str, sid: str): """ - Constructs a StepContext - - :param sid: The SID that identifies the resource to fetch + Initialize the StepContext - :returns: twilio.rest.studio.v1.flow.engagement.step.StepContext - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepContext + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param engagement_sid: The SID of the Engagement with the Step to fetch. + :param sid: The SID of the Step resource to fetch. """ - return StepContext( - self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - sid=sid, + 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 ) - def __repr__(self): + self._step_context: Optional[StepContextList] = None + + def _fetch(self) -> tuple: """ - Provide a friendly representation + Internal helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class StepPage(Page): - """ """ + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> StepInstance: """ - Initialize the StepPage + Fetch the StepInstance - :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 + :returns: The fetched StepInstance """ - super(StepPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = self._fetch() + return StepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], + ) - def get_instance(self, payload): + def fetch_with_http_info(self) -> ApiResponse: """ - Build an instance of StepInstance + Fetch the StepInstance and return response metadata - :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 + :returns: ApiResponse with instance, status code, and headers """ - return StepInstance( + payload, status_code, headers = self._fetch() + instance = 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"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class StepContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, flow_sid, engagement_sid, sid): - """ - Initialize the StepContext - - :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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: twilio.rest.studio.v1.flow.engagement.step.StepContext - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepContext + async def fetch_async(self) -> StepInstance: """ - super(StepContext, self).__init__(version) + Asynchronous coroutine to fetch the StepInstance - # 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 - - def fetch(self): + :returns: The fetched StepInstance """ - Fetch the StepInstance + payload, _, _ = await self._fetch_async() + return StepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], + ) - :returns: The fetched StepInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepInstance + async def fetch_with_http_info_async(self) -> ApiResponse: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronous coroutine to fetch the StepInstance and return response metadata - return StepInstance( + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = StepInstance( self._version, payload, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - sid=self._solution['sid'], + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def step_context(self): + def step_context(self) -> StepContextList: """ Access the step_context - - :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'], + self._solution["flow_sid"], + self._solution["engagement_sid"], + self._solution["sid"], ) return self._step_context - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 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'), - } +class StepPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> StepInstance: + """ + Build an instance of StepInstance + + :param payload: Payload response from the API + """ + + return StepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) - # Context - self._context = None + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class StepList(ListResource): + + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): + """ + Initialize the StepList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to read. + :param engagement_sid: The SID of the Engagement with the Step to read. + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'flow_sid': flow_sid, - 'engagement_sid': engagement_sid, - 'sid': sid or self._properties['sid'], + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, } + self._uri = "/Flows/{flow_sid}/Engagements/{engagement_sid}/Steps".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[StepInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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: StepContext for this StepInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepContext + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = StepContext( - self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_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[StepInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Asynchronously streams StepInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Streams StepInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def flow_sid(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Flow - :rtype: unicode + Asynchronously streams StepInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['flow_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def engagement_sid(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[StepInstance]: """ - :returns: The SID of the Engagement - :rtype: unicode + Lists StepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['engagement_sid'] - @property - def name(self): + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[StepInstance]: """ - :returns: The event that caused the Flow to transition to the Step - :rtype: unicode + Asynchronously lists StepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['name'] - @property - def context(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The current state of the flow - :rtype: dict + Lists StepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['context'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def transitioned_from(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The Widget that preceded the Widget for the Step - :rtype: unicode + Asynchronously lists StepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['transitioned_from'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def transitioned_to(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, + ) -> StepPage: + """ + Retrieve a single page of StepInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of StepInstance """ - :returns: The Widget that will follow the Widget for the Step - :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 StepPage(self._version, response, solution=self._solution) + + async def 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: """ - return self._properties['transitioned_to'] + Asynchronously retrieve a single page of StepInstance 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 StepInstance """ - :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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return StepPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_created'] + Retrieve a single page with response metadata - @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: ApiResponse with StepPage, status code, and headers """ - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = StepPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with StepPage, status code, and headers """ - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = StepPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> StepPage: """ - return self._properties['url'] + Retrieve a specific page of StepInstance 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 StepInstance """ - :returns: The URLs of related resources - :rtype: unicode + response = self._version.domain.twilio.request("GET", target_url) + return StepPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> StepPage: """ - return self._properties['links'] + Asynchronously retrieve a specific page of StepInstance 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 StepInstance """ - Fetch the StepInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return StepPage(self._version, response, solution=self._solution) - :returns: The fetched StepInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepInstance + def get(self, sid: str) -> StepContext: """ - return self._proxy.fetch() + Constructs a StepContext - @property - def step_context(self): + :param sid: The SID of the Step resource to fetch. """ - Access the step_context + return StepContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=sid, + ) - :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextList - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextList + def __call__(self, sid: str) -> StepContext: """ - return self._proxy.step_context + Constructs a StepContext + + :param sid: The SID of the Step resource to fetch. + """ + return StepContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..26f82d470d 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,308 @@ -# 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.api_response import ApiResponse 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 StepContextList(ListResource): - """ """ - - def __init__(self, version, flow_sid, engagement_sid, step_sid): - """ - Initialize the StepContextList +from twilio.base.version import Version - :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.StepContextList - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextList - """ - super(StepContextList, self).__init__(version) +class StepContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the StepContext resource. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar engagement_sid: The SID of the Engagement. + :ivar flow_sid: The SID of the Flow. + :ivar step_sid: The SID of the Step the context is associated with. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + engagement_sid: str, + step_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.engagement_sid: Optional[str] = payload.get("engagement_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.step_sid: Optional[str] = payload.get("step_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "step_sid": step_sid, + } - # Path Solution - self._solution = {'flow_sid': flow_sid, 'engagement_sid': engagement_sid, 'step_sid': step_sid, } + self._context: Optional[StepContextContext] = None - def get(self): + @property + def _proxy(self) -> "StepContextContext": """ - Constructs a StepContextContext + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext + :returns: StepContextContext for this StepContextInstance """ - return StepContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - step_sid=self._solution['step_sid'], - ) + if self._context is None: + self._context = StepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) + return self._context - def __call__(self): + def fetch(self) -> "StepContextInstance": """ - Constructs a StepContextContext + Fetch the StepContextInstance - :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext - """ - return StepContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - step_sid=self._solution['step_sid'], - ) - def __repr__(self): + :returns: The fetched StepContextInstance """ - Provide a friendly representation + return self._proxy.fetch() - :returns: Machine friendly representation - :rtype: str + async def fetch_async(self) -> "StepContextInstance": """ - return '' + Asynchronous coroutine to fetch the StepContextInstance -class StepContextPage(Page): - """ """ + :returns: The fetched StepContextInstance + """ + return await self._proxy.fetch_async() - def __init__(self, version, response, solution): + def fetch_with_http_info(self) -> ApiResponse: """ - Initialize the StepContextPage + Fetch the StepContextInstance with HTTP info - :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 - :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextPage - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextPage + :returns: ApiResponse with instance, status code, and headers """ - super(StepContextPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info() - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of StepContextInstance + Asynchronous coroutine to fetch the StepContextInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return StepContextInstance( - self._version, - payload, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - step_sid=self._solution['step_sid'], - ) + return await self._proxy.fetch_with_http_info_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 StepContextContext(InstanceContext): - """ """ - def __init__(self, version, flow_sid, engagement_sid, step_sid): + def __init__( + self, version: Version, flow_sid: str, engagement_sid: str, step_sid: str + ): """ 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 + :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(StepContextContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'flow_sid': flow_sid, 'engagement_sid': engagement_sid, 'step_sid': step_sid, } - self._uri = '/Flows/{flow_sid}/Engagements/{engagement_sid}/Steps/{step_sid}/Context'.format(**self._solution) + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "step_sid": step_sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{engagement_sid}/Steps/{step_sid}/Context".format( + **self._solution + ) - def fetch(self): + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> StepContextInstance: """ 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, _, _ = self._fetch() 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): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + def fetch_with_http_info(self) -> ApiResponse: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Fetch the StepContextInstance and return response metadata -class StepContextInstance(InstanceResource): - """ """ + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = StepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __init__(self, version, payload, flow_sid, engagement_sid, step_sid): + async def _fetch_async(self) -> tuple: """ - Initialize the StepContextInstance + Internal async helper for fetch operation - :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextInstance + Returns: + tuple: (payload, status_code, headers) """ - 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'), - } + headers = values.of({}) - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'engagement_sid': engagement_sid, 'step_sid': step_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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: StepContextContext for this StepContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext + async def fetch_async(self) -> 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 + Asynchronous coroutine to fetch the StepContextInstance - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def context(self): - """ - :returns: The current state of the flow - :rtype: dict + :returns: The fetched StepContextInstance """ - return self._properties['context'] + payload, _, _ = await self._fetch_async() + return StepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) - @property - def engagement_sid(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: The SID of the Engagement - :rtype: unicode + Asynchronous coroutine to fetch the StepContextInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['engagement_sid'] + payload, status_code, headers = await self._fetch_async() + instance = StepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def flow_sid(self): + def __repr__(self) -> str: """ - :returns: The SID of the Flow - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['flow_sid'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def step_sid(self): + +class StepContextList(ListResource): + + def __init__( + self, version: Version, flow_sid: str, engagement_sid: str, step_sid: str + ): """ - :returns: Step SID - :rtype: unicode + Initialize the StepContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param engagement_sid: The SID of the Engagement with the Step to fetch. + :param step_sid: The SID of the Step to fetch + """ - return self._properties['step_sid'] + super().__init__(version) - @property - def url(self): + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "step_sid": step_sid, + } + + def get(self) -> StepContextContext: """ - :returns: The absolute URL of the resource - :rtype: unicode + Constructs a StepContextContext + """ - 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 3b2269b7cc..5ee77d109e 100644 --- a/twilio/rest/studio/v1/flow/execution/__init__.py +++ b/twilio/rest/studio/v1/flow/execution/__init__.py @@ -1,507 +1,1221 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): - """ """ +class ExecutionInstance(InstanceResource): + + class Status(object): + ACTIVE = "active" + ENDED = "ended" + + """ + :ivar sid: The unique string that we created to identify the Execution resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Execution resource. + :ivar flow_sid: The SID of the Flow. + :ivar contact_sid: The SID of the Contact. + :ivar contact_channel_address: The phone number, SIP address or Client identifier that triggered the Execution. Phone numbers are in E.164 format (e.g. +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar status: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of nested resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.contact_sid: Optional[str] = payload.get("contact_sid") + self.contact_channel_address: Optional[str] = payload.get( + "contact_channel_address" + ) + self.context: Optional[Dict[str, object]] = payload.get("context") + self.status: Optional["ExecutionInstance.Status"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "flow_sid": flow_sid, + "sid": sid or self.sid, + } - def __init__(self, version, flow_sid): + self._context: Optional[ExecutionContext] = None + + @property + def _proxy(self) -> "ExecutionContext": """ - Initialize the ExecutionList + 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 + :returns: ExecutionContext for this ExecutionInstance + """ + if self._context is None: + self._context = ExecutionContext( + self._version, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.studio.v1.flow.execution.ExecutionList - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionList + def delete(self) -> bool: """ - super(ExecutionList, self).__init__(version) + Deletes the ExecutionInstance - # Path Solution - self._solution = {'flow_sid': flow_sid, } - self._uri = '/Flows/{flow_sid}/Executions'.format(**self._solution) - def stream(self, date_created_from=values.unset, date_created_to=values.unset, - limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return self._proxy.delete() - :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) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ExecutionInstance - :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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page( - date_created_from=date_created_from, - date_created_to=date_created_to, - page_size=limits['page_size'], - ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ExecutionInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, date_created_from=values.unset, date_created_to=values.unset, - limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists ExecutionInstance 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.delete_with_http_info() - :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) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ExecutionInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v1.flow.execution.ExecutionInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream( - date_created_from=date_created_from, - date_created_to=date_created_to, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_with_http_info_async() - 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): + def fetch(self) -> "ExecutionInstance": """ - Retrieve a single page of ExecutionInstance records from the API. - Request is executed immediately + Fetch 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: The fetched ExecutionInstance """ - data = values.of({ - 'DateCreatedFrom': serialize.iso8601_datetime(date_created_from), - 'DateCreatedTo': serialize.iso8601_datetime(date_created_to), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "ExecutionInstance": + """ + Asynchronous coroutine to 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 + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of ExecutionInstance - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionPage + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionInstance with HTTP info - return ExecutionPage(self._version, response, self._solution) - def create(self, to, from_, parameters=values.unset): + :returns: ApiResponse with instance, status code, and headers """ - Create the ExecutionInstance + return await self._proxy.fetch_with_http_info_async() + + def update(self, status: "ExecutionInstance.Status") -> "ExecutionInstance": + """ + Update 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 + :param status: - :returns: The created ExecutionInstance - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance + :returns: The updated ExecutionInstance """ - data = values.of({'To': to, 'From': from_, 'Parameters': serialize.object(parameters), }) + return self._proxy.update( + status=status, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> "ExecutionInstance": + """ + Asynchronous coroutine to update the ExecutionInstance - return ExecutionInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) + :param status: - def get(self, sid): + :returns: The updated ExecutionInstance """ - Constructs a ExecutionContext + return await self._proxy.update_async( + status=status, + ) + + def update_with_http_info(self, status: "ExecutionInstance.Status") -> ApiResponse: + """ + Update the ExecutionInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return ExecutionContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + status=status, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, status: "ExecutionInstance.Status" + ) -> ApiResponse: """ - Constructs a ExecutionContext + Asynchronous coroutine to update the ExecutionInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return ExecutionContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + status=status, + ) - def __repr__(self): + @property + def execution_context(self) -> ExecutionContextList: + """ + Access the execution_context + """ + return self._proxy.execution_context + + @property + def steps(self) -> ExecutionStepList: + """ + Access the steps + """ + return self._proxy.steps + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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 + self._solution = { + "flow_sid": flow_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{sid}".format(**self._solution) - def get_instance(self, payload): + self._execution_context: Optional[ExecutionContextList] = None + self._steps: Optional[ExecutionStepList] = None + + def _delete(self) -> tuple: """ - Build an instance of ExecutionInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :returns: twilio.rest.studio.v1.flow.execution.ExecutionInstance - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return ExecutionInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) + Deletes the ExecutionInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the ExecutionInstance and return response metadata -class ExecutionContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, flow_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the ExecutionContext + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + 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) + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ExecutionInstance and return response metadata - # Path Solution - self._solution = {'flow_sid': flow_sid, 'sid': sid, } - self._uri = '/Flows/{flow_sid}/Executions/{sid}'.format(**self._solution) - # Dependents - self._steps = None - self._execution_context = None + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + 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, ) + payload, _, _ = self._fetch() + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ExecutionInstance: + """ + Asynchronous coroutine to fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + payload, _, _ = await self._fetch_async() 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_with_http_info_async(self) -> ApiResponse: """ - Deletes the ExecutionInstance + Asynchronous coroutine to fetch the ExecutionInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def steps(self): + def _update(self, status: "ExecutionInstance.Status") -> tuple: """ - Access the steps + Internal helper for update operation - :returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepList - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepList + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, status: "ExecutionInstance.Status") -> ExecutionInstance: + """ + Update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + payload, _, _ = self._update(status=status) + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info(self, status: "ExecutionInstance.Status") -> ApiResponse: + """ + Update the ExecutionInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, status: "ExecutionInstance.Status") -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> ExecutionInstance: + """ + Asynchronous coroutine to update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + payload, _, _ = await self._update_async(status=status) + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, status: "ExecutionInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ExecutionInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 - :returns: twilio.rest.studio.v1.flow.execution.ExecutionInstance - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation """ - super(ExecutionInstance, 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'), + +class ExecutionList(ListResource): + + def __init__(self, version: Version, flow_sid: str): + """ + Initialize the ExecutionList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, } + self._uri = "/Flows/{flow_sid}/Executions".format(**self._solution) - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: ExecutionContext for this ExecutionInstance - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: """ - if self._context is None: - self._context = ExecutionContext( - self._version, - flow_sid=self._solution['flow_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the ExecutionInstance - @property - def sid(self): + :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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = self._create(to=to, from_=from_, parameters=parameters) + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def create_with_http_info( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ApiResponse: """ - return self._properties['sid'] + Create the ExecutionInstance and return response metadata - @property - def account_sid(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Account that created the resource - :rtype: unicode + payload, status_code, headers = self._create( + to=to, from_=from_, parameters=parameters + ) + instance = ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for create operation - @property - def flow_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the Flow - :rtype: unicode + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: """ - return self._properties['flow_sid'] + Asynchronously create the ExecutionInstance - @property - def contact_sid(self): + :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 """ - :returns: The SID of the Contact - :rtype: unicode + payload, _, _ = await self._create_async( + to=to, from_=from_, parameters=parameters + ) + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + async def create_with_http_info_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ApiResponse: """ - return self._properties['contact_sid'] + Asynchronously create the ExecutionInstance and return response metadata - @property - def contact_channel_address(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The phone number, SIP address or Client identifier that triggered the Execution - :rtype: unicode + payload, status_code, headers = await self._create_async( + to=to, from_=from_, parameters=parameters + ) + instance = ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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]: """ - return self._properties['contact_channel_address'] + 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. - @property - def context(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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 current state of the flow - :rtype: dict + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ExecutionInstance]: """ - return self._properties['context'] + 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. - @property - def status(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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: """ - :returns: The status of the Execution - :rtype: ExecutionInstance.Status + Streams ExecutionInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['status'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) - @property - def date_created(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Asynchronously streams ExecutionInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) - @property - def date_updated(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + 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 self._properties['date_updated'] - @property - def url(self): + 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]: """ - :returns: The absolute URL of the resource - :rtype: unicode + Asynchronously lists ExecutionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['url'] + Lists ExecutionInstance and returns headers from first page - @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: ApiResponse with list of instances, status code, and headers """ - :returns: Nested resource URLs - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['links'] + Asynchronously lists ExecutionInstance and returns headers from first page + + + :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) - def fetch(self): + :returns: ApiResponse with list of instances, status code, and headers """ - Fetch the ExecutionInstance + generator, status_code, headers = await self.stream_with_http_info_async( + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionPage: + """ + Retrieve a single page of ExecutionInstance records from the API. + Request is executed immediately - :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"}) + + headers["Accept"] = "application/json" - def delete(self): + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionPage(self._version, response, solution=self._solution) + + async def page_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionPage: + """ + Asynchronously retrieve a single page of ExecutionInstance records from the API. + Request is executed immediately + + :param date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionInstance """ - Deletes the ExecutionInstance + data = values.of( + { + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :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 ExecutionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ExecutionPage, status code, and headers + """ + data = values.of( + { + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ExecutionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ExecutionPage, status code, and headers + """ + data = values.of( + { + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ExecutionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ExecutionPage: """ - return self._proxy.delete() + Retrieve a specific page of ExecutionInstance records from the API. + Request is executed immediately - @property - def steps(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionInstance """ - Access the steps + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionPage(self._version, response, solution=self._solution) - :returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepList - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepList + async def get_page_async(self, target_url: str) -> ExecutionPage: """ - return self._proxy.steps + Asynchronously retrieve a specific page of ExecutionInstance records from the API. + Request is executed immediately - @property - def execution_context(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionInstance """ - Access the execution_context + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionPage(self._version, response, solution=self._solution) - :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList + def get(self, sid: str) -> ExecutionContext: """ - return self._proxy.execution_context + Constructs a ExecutionContext + + :param sid: The SID of the Execution resource to update. + """ + return ExecutionContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ExecutionContext: + """ + Constructs a ExecutionContext + + :param sid: The SID of the Execution resource to update. + """ + return ExecutionContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..d12c6b3f93 100644 --- a/twilio/rest/studio/v1/flow/execution/execution_context.py +++ b/twilio/rest/studio/v1/flow/execution/execution_context.py @@ -1,263 +1,289 @@ -# 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.api_response import ApiResponse 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 ExecutionContextList(ListResource): - """ """ - - def __init__(self, version, flow_sid, execution_sid): - """ - Initialize the ExecutionContextList +from twilio.base.version import Version - :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: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList - """ - super(ExecutionContextList, self).__init__(version) +class ExecutionContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionContext resource. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar flow_sid: The SID of the Flow. + :ivar execution_sid: The SID of the context's Execution resource. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } - # Path Solution - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, } + self._context: Optional[ExecutionContextContext] = None - def get(self): + @property + def _proxy(self) -> "ExecutionContextContext": """ - Constructs a ExecutionContextContext + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext + :returns: ExecutionContextContext for this ExecutionContextInstance """ - return ExecutionContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - ) + if self._context is None: + self._context = ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + return self._context - def __call__(self): + def fetch(self) -> "ExecutionContextInstance": """ - Constructs a ExecutionContextContext + Fetch the ExecutionContextInstance - :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext - """ - return ExecutionContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - ) - def __repr__(self): + :returns: The fetched ExecutionContextInstance """ - Provide a friendly representation + return self._proxy.fetch() - :returns: Machine friendly representation - :rtype: str + async def fetch_async(self) -> "ExecutionContextInstance": """ - return '' + Asynchronous coroutine to fetch the ExecutionContextInstance -class ExecutionContextPage(Page): - """ """ + :returns: The fetched ExecutionContextInstance + """ + return await self._proxy.fetch_async() - def __init__(self, version, response, solution): + def fetch_with_http_info(self) -> ApiResponse: """ - Initialize the ExecutionContextPage + Fetch the ExecutionContextInstance with HTTP info - :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_context.ExecutionContextPage - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextPage + :returns: ApiResponse with instance, status code, and headers """ - super(ExecutionContextPage, self).__init__(version, response) + return self._proxy.fetch_with_http_info() - # Path Solution - self._solution = solution - - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of ExecutionContextInstance + Asynchronous coroutine to fetch the ExecutionContextInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return ExecutionContextInstance( - self._version, - payload, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - ) + return await self._proxy.fetch_with_http_info_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 ExecutionContextContext(InstanceContext): - """ """ - def __init__(self, version, flow_sid, execution_sid): + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ 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 - - :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution context to fetch. + :param execution_sid: The SID of the Execution context to fetch. """ - super(ExecutionContextContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, } - self._uri = '/Flows/{flow_sid}/Executions/{execution_sid}/Context'.format(**self._solution) + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Context".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ExecutionContextInstance: """ 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, _, _ = self._fetch() 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 + def fetch_with_http_info(self) -> ApiResponse: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Fetch the ExecutionContextInstance and return response metadata -class ExecutionContextInstance(InstanceResource): - """ """ + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __init__(self, version, payload, flow_sid, execution_sid): + async def _fetch_async(self) -> tuple: """ - Initialize the ExecutionContextInstance + Internal async helper for fetch operation - :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextInstance + Returns: + tuple: (payload, status_code, headers) """ - 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'), - } + headers = values.of({}) - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: ExecutionContextContext for this ExecutionContextInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext + async def fetch_async(self) -> 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 + Asynchronous coroutine to fetch the ExecutionContextInstance - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + + :returns: The fetched ExecutionContextInstance """ - return self._properties['account_sid'] + payload, _, _ = await self._fetch_async() + return ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) - @property - def context(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: The current state of the flow - :rtype: dict + Asynchronous coroutine to fetch the ExecutionContextInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['context'] + payload, status_code, headers = await self._fetch_async() + instance = ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def flow_sid(self): + def __repr__(self) -> str: """ - :returns: The SID of the Flow - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['flow_sid'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def execution_sid(self): + +class ExecutionContextList(ListResource): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ - :returns: The SID of the Execution - :rtype: unicode + Initialize the ExecutionContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution context to fetch. + :param execution_sid: The SID of the Execution context to fetch. + """ - return self._properties['execution_sid'] + super().__init__(version) - @property - def url(self): + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + + def get(self) -> ExecutionContextContext: """ - :returns: The absolute URL of the resource - :rtype: unicode + Constructs a ExecutionContextContext + """ - 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 4c474736cb..d09adb9984 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,745 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): - """ """ +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 type: The type of the widget that was executed. + :ivar date_created: 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.type: Optional[str] = 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.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") - def __init__(self, version, flow_sid, execution_sid): - """ - Initialize the ExecutionStepList + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "sid": sid or self.sid, + } - :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._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'], limits['page_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): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of ExecutionStepInstance records from the API. - Request is executed immediately + Fetch the ExecutionStepInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ExecutionStepInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepPage + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionStepInstance with HTTP info - return ExecutionStepPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - 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 + return await self._proxy.fetch_with_http_info_async() - :returns: Page of ExecutionStepInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepPage + @property + def step_context(self) -> ExecutionStepContextList: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Access the step_context + """ + return self._proxy.step_context - return ExecutionStepPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a ExecutionStepContext + 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.studio.v1.flow.execution.execution_step.ExecutionStepContext - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext - """ - return ExecutionStepContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - sid=sid, - ) +class ExecutionStepContext(InstanceContext): - def __call__(self, sid): + def __init__(self, version: Version, flow_sid: str, execution_sid: str, sid: str): """ - Constructs a ExecutionStepContext - - :param sid: The unique string that identifies the resource + Initialize the ExecutionStepContext - :returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param sid: The SID of the ExecutionStep resource to fetch. """ - return ExecutionStepContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - sid=sid, + 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 ) - def __repr__(self): + self._step_context: Optional[ExecutionStepContextList] = None + + def _fetch(self) -> tuple: """ - Provide a friendly representation + Internal helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class ExecutionStepPage(Page): - """ """ + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> ExecutionStepInstance: """ - Initialize the ExecutionStepPage + Fetch the ExecutionStepInstance - :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 + :returns: The fetched ExecutionStepInstance """ - super(ExecutionStepPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = self._fetch() + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) - def get_instance(self, payload): + def fetch_with_http_info(self) -> ApiResponse: """ - Build an instance of ExecutionStepInstance + Fetch the ExecutionStepInstance and return response metadata - :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 + :returns: ApiResponse with instance, status code, and headers """ - return ExecutionStepInstance( + payload, status_code, headers = self._fetch() + instance = 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"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class ExecutionStepContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, flow_sid, execution_sid, sid): - """ - Initialize the ExecutionStepContext - - :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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext + async def fetch_async(self) -> ExecutionStepInstance: """ - super(ExecutionStepContext, self).__init__(version) + Asynchronous coroutine to fetch the ExecutionStepInstance - # 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 - - def fetch(self): + :returns: The fetched ExecutionStepInstance """ - Fetch the ExecutionStepInstance + payload, _, _ = await self._fetch_async() + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) - :returns: The fetched ExecutionStepInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance + async def fetch_with_http_info_async(self) -> ApiResponse: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronous coroutine to fetch the ExecutionStepInstance and return response metadata - return ExecutionStepInstance( + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ExecutionStepInstance( self._version, payload, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - sid=self._solution['sid'], + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def step_context(self): + def step_context(self) -> ExecutionStepContextList: """ Access the step_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 """ 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'], + self._solution["flow_sid"], + self._solution["execution_sid"], + self._solution["sid"], ) return self._step_context - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 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'), - } +class ExecutionStepPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ExecutionStepInstance: + """ + Build an instance of ExecutionStepInstance + + :param payload: Payload response from the API + """ + + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) - # Context - self._context = None + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ExecutionStepList(ListResource): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): + """ + Initialize the ExecutionStepList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Steps to read. + :param execution_sid: The SID of the Execution with the Steps to read. + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'flow_sid': flow_sid, - 'execution_sid': execution_sid, - 'sid': sid or self._properties['sid'], + "flow_sid": flow_sid, + "execution_sid": execution_sid, } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExecutionStepInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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: 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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = ExecutionStepContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_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[ExecutionStepInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Asynchronously streams ExecutionStepInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Streams ExecutionStepInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def flow_sid(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Flow - :rtype: unicode + Asynchronously streams ExecutionStepInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['flow_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def execution_sid(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionStepInstance]: """ - :returns: The SID of the Execution - :rtype: unicode + Lists ExecutionStepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['execution_sid'] - @property - def name(self): + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionStepInstance]: """ - :returns: The event that caused the Flow to transition to the Step - :rtype: unicode + Asynchronously lists ExecutionStepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['name'] - @property - def context(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The current state of the flow - :rtype: dict + Lists ExecutionStepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['context'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def transitioned_from(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The Widget that preceded the Widget for the Step - :rtype: unicode + Asynchronously lists ExecutionStepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['transitioned_from'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def transitioned_to(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, + ) -> ExecutionStepPage: + """ + Retrieve a single page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionStepInstance """ - :returns: The Widget that will follow the Widget for the Step - :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 ExecutionStepPage(self._version, response, solution=self._solution) + + async def 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: """ - return self._properties['transitioned_to'] + Asynchronously retrieve a single page of ExecutionStepInstance 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 ExecutionStepInstance """ - :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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionStepPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_created'] + Retrieve a single page with response metadata - @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: ApiResponse with ExecutionStepPage, status code, and headers """ - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ExecutionStepPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with ExecutionStepPage, status code, and headers """ - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ExecutionStepPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ExecutionStepPage: """ - return self._properties['url'] + Retrieve a specific page of ExecutionStepInstance 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 ExecutionStepInstance """ - :returns: The URLs of related resources - :rtype: unicode + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionStepPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ExecutionStepPage: """ - return self._properties['links'] + Asynchronously retrieve a specific page of ExecutionStepInstance 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 ExecutionStepInstance """ - Fetch the ExecutionStepInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionStepPage(self._version, response, solution=self._solution) - :returns: The fetched ExecutionStepInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance + def get(self, sid: str) -> ExecutionStepContext: """ - return self._proxy.fetch() + Constructs a ExecutionStepContext - @property - def step_context(self): + :param sid: The SID of the ExecutionStep resource to fetch. """ - Access the step_context + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=sid, + ) - :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 __call__(self, sid: str) -> ExecutionStepContext: """ - return self._proxy.step_context + Constructs a ExecutionStepContext + + :param sid: The SID of the ExecutionStep resource to fetch. + """ + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..469a2e48c4 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,308 @@ -# 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.api_response import ApiResponse 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 ExecutionStepContextList(ListResource): - """ """ - - def __init__(self, version, flow_sid, execution_sid, step_sid): - """ - Initialize the ExecutionStepContextList +from twilio.base.version import Version - :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.ExecutionStepContextList - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList - """ - super(ExecutionStepContextList, self).__init__(version) +class ExecutionStepContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStepContext resource. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar execution_sid: The SID of the context's Execution resource. + :ivar flow_sid: The SID of the Flow. + :ivar step_sid: The SID of the Step that the context is associated with. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + step_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.step_sid: Optional[str] = payload.get("step_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } - # Path Solution - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, 'step_sid': step_sid, } + self._context: Optional[ExecutionStepContextContext] = None - def get(self): + @property + def _proxy(self) -> "ExecutionStepContextContext": """ - Constructs a ExecutionStepContextContext + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: 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: ExecutionStepContextContext for this ExecutionStepContextInstance """ - return ExecutionStepContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - step_sid=self._solution['step_sid'], - ) + if self._context is None: + self._context = ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + return self._context - def __call__(self): + def fetch(self) -> "ExecutionStepContextInstance": """ - Constructs a ExecutionStepContextContext + Fetch the ExecutionStepContextInstance - :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 - """ - 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): + :returns: The fetched ExecutionStepContextInstance """ - Provide a friendly representation + return self._proxy.fetch() - :returns: Machine friendly representation - :rtype: str + async def fetch_async(self) -> "ExecutionStepContextInstance": """ - return '' + Asynchronous coroutine to fetch the ExecutionStepContextInstance -class ExecutionStepContextPage(Page): - """ """ + :returns: The fetched ExecutionStepContextInstance + """ + return await self._proxy.fetch_async() - def __init__(self, version, response, solution): + def fetch_with_http_info(self) -> ApiResponse: """ - Initialize the ExecutionStepContextPage + Fetch the ExecutionStepContextInstance with HTTP info - :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 - :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 + :returns: ApiResponse with instance, status code, and headers """ - super(ExecutionStepContextPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info() - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of ExecutionStepContextInstance + Asynchronous coroutine to fetch the ExecutionStepContextInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return ExecutionStepContextInstance( - self._version, - payload, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - step_sid=self._solution['step_sid'], - ) + return await self._proxy.fetch_with_http_info_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 ExecutionStepContextContext(InstanceContext): - """ """ - def __init__(self, version, flow_sid, execution_sid, step_sid): + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): """ 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 + :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(ExecutionStepContextContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, 'step_sid': step_sid, } - self._uri = '/Flows/{flow_sid}/Executions/{execution_sid}/Steps/{step_sid}/Context'.format(**self._solution) + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps/{step_sid}/Context".format( + **self._solution + ) - def fetch(self): + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ExecutionStepContextInstance: """ 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, _, _ = self._fetch() 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): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + def fetch_with_http_info(self) -> ApiResponse: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Fetch the ExecutionStepContextInstance and return response metadata -class ExecutionStepContextInstance(InstanceResource): - """ """ + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __init__(self, version, payload, flow_sid, execution_sid, step_sid): + async def _fetch_async(self) -> tuple: """ - Initialize the ExecutionStepContextInstance + Internal async helper for fetch operation - :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: + tuple: (payload, status_code, headers) """ - 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'), - } + headers = values.of({}) - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, 'step_sid': step_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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: ExecutionStepContextContext for this ExecutionStepContextInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext + async def fetch_async(self) -> 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 + Asynchronous coroutine to fetch the ExecutionStepContextInstance - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def context(self): - """ - :returns: The current state of the flow - :rtype: dict + :returns: The fetched ExecutionStepContextInstance """ - return self._properties['context'] + payload, _, _ = await self._fetch_async() + return ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) - @property - def execution_sid(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: The SID of the Execution - :rtype: unicode + Asynchronous coroutine to fetch the ExecutionStepContextInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['execution_sid'] + payload, status_code, headers = await self._fetch_async() + instance = ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def flow_sid(self): + def __repr__(self) -> str: """ - :returns: The SID of the Flow - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['flow_sid'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def step_sid(self): + +class ExecutionStepContextList(ListResource): + + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): """ - :returns: Step SID - :rtype: unicode + Initialize the ExecutionStepContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param step_sid: The SID of the Step to fetch. + """ - return self._properties['step_sid'] + super().__init__(version) - @property - def url(self): + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + + def get(self) -> ExecutionStepContextContext: """ - :returns: The absolute URL of the resource - :rtype: unicode + Constructs a ExecutionStepContextContext + """ - 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 3f1bdaf943..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_valid = 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_valid(self): - """ - :rtype: twilio.rest.studio.v2.flow_validate.FlowValidateList - """ - if self._flow_valid is None: - self._flow_valid = FlowValidateList(self) - return self._flow_valid + 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 4e24fc190a..c13e10be4c 100644 --- a/twilio/rest/studio/v2/flow/__init__.py +++ b/twilio/rest/studio/v2/flow/__init__.py @@ -1,569 +1,1321 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): + + 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 author_sid: The SID of the User that created or last updated the Flow. + :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.author_sid: Optional[str] = payload.get("author_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.definition: Optional[Dict[str, object]] = payload.get("definition") + self.status: Optional["FlowInstance.Status"] = payload.get("status") + self.revision: Optional[int] = deserialize.integer(payload.get("revision")) + self.commit_message: Optional[str] = payload.get("commit_message") + self.valid: Optional[bool] = payload.get("valid") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + self.warnings: Optional[List[Dict[str, object]]] = payload.get("warnings") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } - def __init__(self, version): + self._context: Optional[FlowContext] = None + + @property + def _proxy(self) -> "FlowContext": """ - Initialize the FlowList + 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: FlowContext for this FlowInstance + """ + if self._context is None: + self._context = FlowContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.studio.v2.flow.FlowList - :rtype: twilio.rest.studio.v2.flow.FlowList + def delete(self) -> bool: """ - super(FlowList, self).__init__(version) + Deletes the FlowInstance - # Path Solution - self._solution = {} - self._uri = '/Flows'.format(**self._solution) - def create(self, friendly_name, status, definition, - commit_message=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the FlowInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FlowInstance - :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 await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FlowInstance with HTTP info - return FlowInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlowInstance with HTTP info - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "FlowInstance": + """ + Fetch the FlowInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "FlowInstance": + """ + Asynchronous coroutine to fetch the FlowInstance - :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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of FlowInstance records from the API. - Request is executed immediately + Fetch the FlowInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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.v2.flow.FlowPage + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowInstance with HTTP info - return FlowPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of FlowInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + 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, + author_sid: Union[str, object] = values.unset, + ) -> "FlowInstance": + """ + Update the FlowInstance - :returns: Page of FlowInstance - :rtype: twilio.rest.studio.v2.flow.FlowPage + :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. + :param author_sid: The SID of the User that created or last updated the Flow. + + :returns: The updated FlowInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, ) - return FlowPage(self._version, response, self._solution) + 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, + author_sid: Union[str, object] = values.unset, + ) -> "FlowInstance": + """ + Asynchronous coroutine to update the FlowInstance + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created or last updated the Flow. - def get(self, sid): + :returns: The updated FlowInstance """ - Constructs a FlowContext + return await self._proxy.update_async( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + + def update_with_http_info( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the FlowInstance with HTTP info - :param sid: The SID that identifies the resource to fetch + :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. + :param author_sid: The SID of the User that created or last updated the Flow. - :returns: twilio.rest.studio.v2.flow.FlowContext - :rtype: twilio.rest.studio.v2.flow.FlowContext + :returns: ApiResponse with instance, status code, and headers """ - return FlowContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) - def __call__(self, sid): + async def update_with_http_info_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, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Constructs a FlowContext + Asynchronous coroutine to update the FlowInstance with HTTP info - :param sid: The SID that identifies the resource to fetch + :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. + :param author_sid: The SID of the User that created or last updated the Flow. - :returns: twilio.rest.studio.v2.flow.FlowContext - :rtype: twilio.rest.studio.v2.flow.FlowContext + :returns: ApiResponse with instance, status code, and headers """ - return FlowContext(self._version, sid=sid, ) + return await self._proxy.update_with_http_info_async( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) - def __repr__(self): + @property + def executions(self) -> ExecutionList: + """ + Access the executions + """ + return self._proxy.executions + + @property + def revisions(self) -> FlowRevisionList: + """ + Access the revisions + """ + return self._proxy.revisions + + @property + def test_users(self) -> FlowTestUserList: + """ + Access the test_users + """ + return self._proxy.test_users + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class FlowPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class FlowContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the FlowPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the FlowContext - :returns: twilio.rest.studio.v2.flow.FlowPage - :rtype: twilio.rest.studio.v2.flow.FlowPage + :param version: Version that contains the resource + :param sid: The SID of the Flow resource to fetch. """ - super(FlowPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Flows/{sid}".format(**self._solution) - def get_instance(self, payload): + self._executions: Optional[ExecutionList] = None + self._revisions: Optional[FlowRevisionList] = None + self._test_users: Optional[FlowTestUserList] = None + + def _delete(self) -> tuple: """ - Build an instance of FlowInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: twilio.rest.studio.v2.flow.FlowInstance - :rtype: twilio.rest.studio.v2.flow.FlowInstance + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return FlowInstance(self._version, payload, ) + Deletes the FlowInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the FlowInstance and return response metadata -class FlowContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the FlowContext - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch + headers = values.of({}) - :returns: twilio.rest.studio.v2.flow.FlowContext - :rtype: twilio.rest.studio.v2.flow.FlowContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(FlowContext, self).__init__(version) + Asynchronous coroutine that deletes the FlowInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Flows/{sid}'.format(**self._solution) - # Dependents - self._revisions = None - self._test_users = None - self._executions = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success - def update(self, status, friendly_name=values.unset, definition=values.unset, - commit_message=values.unset): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Update the FlowInstance + Asynchronous coroutine that deletes the FlowInstance and return response metadata - :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 - :returns: The updated FlowInstance - :rtype: twilio.rest.studio.v2.flow.FlowInstance + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: """ - data = values.of({ - 'Status': status, - 'FriendlyName': friendly_name, - 'Definition': serialize.object(definition), - 'CommitMessage': commit_message, - }) + Internal helper for fetch operation - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + Returns: + tuple: (payload, status_code, headers) + """ - return FlowInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> FlowInstance: """ Fetch the FlowInstance + :returns: The fetched FlowInstance - :rtype: twilio.rest.studio.v2.flow.FlowInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowInstance and return response metadata - return FlowInstance(self._version, payload, sid=self._solution['sid'], ) - def delete(self): + :returns: ApiResponse with instance, status code, and headers """ - Deletes the FlowInstance + payload, status_code, headers = self._fetch() + instance = FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._version.delete(method='DELETE', uri=self._uri, ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> FlowInstance: + """ + Asynchronous coroutine to fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + payload, _, _ = await self._fetch_async() + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + author_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + "AuthorSid": author_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + author_sid: Union[str, object] = values.unset, + ) -> FlowInstance: + """ + Update the FlowInstance + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created or last updated the Flow. + + :returns: The updated FlowInstance + """ + payload, _, _ = self._update( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + return FlowInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the FlowInstance and return response metadata + + :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. + :param author_sid: The SID of the User that created or last updated the Flow. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + instance = FlowInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + author_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + "AuthorSid": author_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + author_sid: Union[str, object] = values.unset, + ) -> FlowInstance: + """ + Asynchronous coroutine to update the FlowInstance + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created or last updated the Flow. + + :returns: The updated FlowInstance + """ + payload, _, _ = await self._update_async( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + return FlowInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FlowInstance and return response metadata + + :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. + :param author_sid: The SID of the User that created or last updated the Flow. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + instance = FlowInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def revisions(self): + def executions(self) -> ExecutionList: """ - Access the revisions + Access the executions + """ + if self._executions is None: + self._executions = ExecutionList( + self._version, + self._solution["sid"], + ) + return self._executions - :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionList - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionList + @property + def revisions(self) -> FlowRevisionList: + """ + Access the revisions """ 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: twilio.rest.studio.v2.flow.execution.ExecutionList - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionList + :returns: Machine friendly representation """ - if self._executions is None: - self._executions = ExecutionList(self._version, flow_sid=self._solution['sid'], ) - return self._executions + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FlowPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FlowInstance: + """ + Build an instance of FlowInstance - def __repr__(self): + :param payload: Payload response from the API + """ + + return FlowInstance(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 FlowInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class FlowList(ListResource): - class Status(object): - DRAFT = "draft" - PUBLISHED = "published" + def __init__(self, version: Version): + """ + Initialize the FlowList - 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'), - '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'), - } + :param version: Version that contains the resource - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + """ + super().__init__(version) - @property - def _proxy(self): + self._uri = "/Flows" + + def _create( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> tuple: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Internal helper for create operation - :returns: FlowContext for this FlowInstance - :rtype: twilio.rest.studio.v2.flow.FlowContext + Returns: + tuple: (payload, status_code, headers) """ - if self._context is None: - self._context = FlowContext(self._version, sid=self._solution['sid'], ) - return self._context - @property - def sid(self): + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + "AuthorSid": author_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> FlowInstance: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Create the FlowInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created the Flow. + + :returns: The created FlowInstance """ - return self._properties['sid'] + payload, _, _ = self._create( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + return FlowInstance(self._version, payload) - @property - def account_sid(self): + def create_with_http_info( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Create the FlowInstance and return response metadata + + :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. + :param author_sid: The SID of the User that created the Flow. + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['account_sid'] + payload, status_code, headers = self._create( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + instance = FlowInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + "AuthorSid": author_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def friendly_name(self): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> FlowInstance: """ - :returns: The string that you assigned to describe the Flow - :rtype: unicode + Asynchronously create the FlowInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created the Flow. + + :returns: The created FlowInstance """ - return self._properties['friendly_name'] + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + return FlowInstance(self._version, payload) - @property - def definition(self): + async def create_with_http_info_async( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: """ - :returns: JSON representation of flow definition - :rtype: dict + Asynchronously create the FlowInstance and return response metadata + + :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. + :param author_sid: The SID of the User that created the Flow. + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['definition'] + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + instance = FlowInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def status(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FlowInstance]: """ - :returns: The status of the Flow - :rtype: FlowInstance.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. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = self.page(page_size=limits["page_size"]) - @property - def revision(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FlowInstance]: """ - :returns: The latest revision number of the Flow's definition - :rtype: unicode + Asynchronously streams FlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['revision'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def commit_message(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: Description on change made in the revision - :rtype: unicode + Streams FlowInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['commit_message'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def valid(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: Boolean if the flow definition is valid - :rtype: bool + Asynchronously streams FlowInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['valid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def errors(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowInstance]: """ - :returns: List of error in the flow definition - :rtype: dict + Lists FlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['errors'] - @property - def date_created(self): + return 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]: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Asynchronously lists FlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['date_created'] - @property - def date_updated(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Lists FlowInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_updated'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def webhook_url(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The webhook_url - :rtype: unicode + Asynchronously lists FlowInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['webhook_url'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> 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"}) + + headers["Accept"] = "application/json" - def update(self, status, friendly_name=values.unset, definition=values.unset, - commit_message=values.unset): + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlowPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Update the FlowInstance + Retrieve a single page with response metadata - :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 - :returns: The updated 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: ApiResponse with FlowPage, status code, and headers """ - 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers ) + page = FlowPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - def fetch(self): + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Fetch the FlowInstance + Asynchronously retrieve a single page with response metadata - :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: ApiResponse with FlowPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FlowPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 3b760c0159..0a0bfa6fed 100644 --- a/twilio/rest/studio/v2/flow/execution/__init__.py +++ b/twilio/rest/studio/v2/flow/execution/__init__.py @@ -1,502 +1,1263 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +class ExecutionInstance(InstanceResource): + + class Status(object): + ACTIVE = "active" + ENDED = "ended" - def __init__(self, version, flow_sid): + """ + :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 contact_sid: The SID of the Contact. + :ivar flow_version: The Flow version number at the time of Execution creation. + :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 initiated_by: The SID or identifier that triggered this Execution. For example, a Call SID if triggered by an incoming call, a Message SID if triggered by an incoming message, a Request SID if triggered by a REST API request, and so on. + :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.contact_sid: Optional[str] = payload.get("contact_sid") + self.flow_version: Optional[int] = deserialize.integer( + payload.get("flow_version") + ) + 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.initiated_by: Optional[str] = payload.get("initiated_by") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "flow_sid": flow_sid, + "sid": sid or self.sid, + } + + self._context: Optional[ExecutionContext] = None + + @property + def _proxy(self) -> "ExecutionContext": """ - Initialize the ExecutionList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid + :returns: ExecutionContext for this ExecutionInstance + """ + if self._context is None: + self._context = ExecutionContext( + self._version, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.studio.v2.flow.execution.ExecutionList - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionList + def delete(self) -> bool: """ - super(ExecutionList, self).__init__(version) + Deletes the ExecutionInstance - # Path Solution - self._solution = {'flow_sid': flow_sid, } - self._uri = '/Flows/{flow_sid}/Executions'.format(**self._solution) - def stream(self, date_created_from=values.unset, date_created_to=values.unset, - limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return self._proxy.delete() - :param datetime date_created_from: The date_created_from - :param datetime date_created_to: The date_created_to - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 ExecutionInstance - :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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page( - date_created_from=date_created_from, - date_created_to=date_created_to, - page_size=limits['page_size'], - ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ExecutionInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, date_created_from=values.unset, date_created_to=values.unset, - limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists ExecutionInstance 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.delete_with_http_info() - :param datetime date_created_from: The date_created_from - :param datetime date_created_to: The date_created_to - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ExecutionInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v2.flow.execution.ExecutionInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream( - date_created_from=date_created_from, - date_created_to=date_created_to, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_with_http_info_async() - 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): + def fetch(self) -> "ExecutionInstance": """ - Retrieve a single page of ExecutionInstance records from the API. - Request is executed immediately + Fetch the ExecutionInstance - :param datetime date_created_from: The date_created_from - :param datetime date_created_to: The date_created_to - :param str page_token: PageToken provided by the API - :param int page_number: 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: The fetched ExecutionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionInstance": """ - data = values.of({ - 'DateCreatedFrom': serialize.iso8601_datetime(date_created_from), - 'DateCreatedTo': serialize.iso8601_datetime(date_created_to), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Asynchronous coroutine to fetch the ExecutionInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return ExecutionPage(self._version, response, self._solution) + :returns: The fetched ExecutionInstance + """ + return await self._proxy.fetch_async() - def get_page(self, target_url): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a specific page of ExecutionInstance records from the API. - Request is executed immediately + Fetch the ExecutionInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionPage + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionInstance with HTTP info - return ExecutionPage(self._version, response, self._solution) - def create(self, to, from_, parameters=values.unset): + :returns: ApiResponse with instance, status code, and headers """ - Create the ExecutionInstance + return await self._proxy.fetch_with_http_info_async() - :param unicode to: The to - :param unicode from_: The from - :param dict parameters: The parameters + def update(self, status: "ExecutionInstance.Status") -> "ExecutionInstance": + """ + Update the ExecutionInstance - :returns: The created ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionInstance + :param status: + + :returns: The updated ExecutionInstance """ - data = values.of({'To': to, 'From': from_, 'Parameters': serialize.object(parameters), }) + return self._proxy.update( + status=status, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> "ExecutionInstance": + """ + Asynchronous coroutine to update the ExecutionInstance - return ExecutionInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) + :param status: - def get(self, sid): + :returns: The updated ExecutionInstance """ - Constructs a ExecutionContext + return await self._proxy.update_async( + status=status, + ) - :param sid: The sid + def update_with_http_info(self, status: "ExecutionInstance.Status") -> ApiResponse: + """ + Update the ExecutionInstance with HTTP info + + :param status: - :returns: twilio.rest.studio.v2.flow.execution.ExecutionContext - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionContext + :returns: ApiResponse with instance, status code, and headers """ - return ExecutionContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + status=status, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, status: "ExecutionInstance.Status" + ) -> ApiResponse: """ - Constructs a ExecutionContext + Asynchronous coroutine to update the ExecutionInstance with HTTP info + + :param status: - :param sid: The sid + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) - :returns: twilio.rest.studio.v2.flow.execution.ExecutionContext - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionContext + @property + def execution_context(self) -> ExecutionContextList: + """ + Access the execution_context + """ + return self._proxy.execution_context + + @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 flow_sid + 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 + self._solution = { + "flow_sid": flow_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{sid}".format(**self._solution) + + self._execution_context: Optional[ExecutionContextList] = None + self._steps: Optional[ExecutionStepList] = None - def get_instance(self, payload): + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of ExecutionInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.studio.v2.flow.execution.ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return ExecutionInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) + Deletes the ExecutionInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the ExecutionInstance and return response metadata -class ExecutionContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, flow_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the ExecutionContext + Internal async helper for delete operation - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param sid: The sid + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.studio.v2.flow.execution.ExecutionContext - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionContext + async def delete_async(self) -> bool: """ - super(ExecutionContext, self).__init__(version) + Asynchronous coroutine that deletes the ExecutionInstance - # Path Solution - self._solution = {'flow_sid': flow_sid, 'sid': sid, } - self._uri = '/Flows/{flow_sid}/Executions/{sid}'.format(**self._solution) - # Dependents - self._steps = None - self._execution_context = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ExecutionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> ExecutionInstance: """ Fetch the ExecutionInstance + + :returns: The fetched ExecutionInstance + """ + payload, _, _ = self._fetch() + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ExecutionInstance: + """ + Asynchronous coroutine to fetch the ExecutionInstance + + :returns: The fetched ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = await self._fetch_async() + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionInstance and return response metadata + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, status: "ExecutionInstance.Status") -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, status: "ExecutionInstance.Status") -> ExecutionInstance: + """ + Update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + payload, _, _ = self._update(status=status) 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): + def update_with_http_info(self, status: "ExecutionInstance.Status") -> ApiResponse: """ - Deletes the ExecutionInstance + Update the ExecutionInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param status: + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = self._update(status=status) + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def steps(self): + async def _update_async(self, status: "ExecutionInstance.Status") -> tuple: """ - Access the steps + Internal async helper for update operation - :returns: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepList - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepList + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> ExecutionInstance: + """ + Asynchronous coroutine to update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + payload, _, _ = await self._update_async(status=status) + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, status: "ExecutionInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ExecutionInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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): + + def get_instance(self, payload: Dict[str, Any]) -> ExecutionInstance: + """ + Build an instance of ExecutionInstance + + :param payload: Payload response from the API + """ + + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" - class Status(object): - ACTIVE = "active" - ENDED = "ended" - def __init__(self, version, payload, flow_sid, sid=None): +class ExecutionList(ListResource): + + def __init__(self, version: Version, flow_sid: str): """ - Initialize the ExecutionInstance + Initialize the ExecutionList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution resources to read. - :returns: twilio.rest.studio.v2.flow.execution.ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionInstance """ - super(ExecutionInstance, self).__init__(version) + super().__init__(version) - # 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'), + # Path Solution + self._solution = { + "flow_sid": flow_sid, } + self._uri = "/Flows/{flow_sid}/Executions".format(**self._solution) - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: ExecutionContext for this ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: """ - if self._context is None: - self._context = ExecutionContext( - self._version, - flow_sid=self._solution['flow_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the ExecutionInstance - @property - def sid(self): + :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 """ - :returns: The sid - :rtype: unicode + payload, _, _ = self._create(to=to, from_=from_, parameters=parameters) + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def create_with_http_info( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ApiResponse: """ - return self._properties['sid'] + Create the ExecutionInstance and return response metadata - @property - def account_sid(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The account_sid - :rtype: unicode + payload, status_code, headers = self._create( + to=to, from_=from_, parameters=parameters + ) + instance = ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> tuple: """ - return self._properties['account_sid'] + Internal async helper for create operation - @property - def flow_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The flow_sid - :rtype: unicode + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: """ - return self._properties['flow_sid'] + Asynchronously create the ExecutionInstance - @property - def contact_channel_address(self): + :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 """ - :returns: The contact_channel_address - :rtype: unicode + payload, _, _ = await self._create_async( + to=to, from_=from_, parameters=parameters + ) + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + async def create_with_http_info_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ApiResponse: """ - return self._properties['contact_channel_address'] + Asynchronously create the ExecutionInstance and return response metadata - @property - def context(self): + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + to=to, from_=from_, parameters=parameters + ) + instance = ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + 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 context - :rtype: dict + 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 "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :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['context'] + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) - @property - def status(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + 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 status - :rtype: ExecutionInstance.Status + 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 "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :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['status'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) - @property - def date_created(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + 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, + ) -> tuple: """ - :returns: The date_created - :rtype: datetime + Streams ExecutionInstance and returns headers from first page + + + :param "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) - @property - def date_updated(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + 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, + ) -> tuple: """ - :returns: The date_updated - :rtype: datetime + Asynchronously streams ExecutionInstance and returns headers from first page + + + :param "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) - @property - def url(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + 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 url - :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 "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :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( + status=status, + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + 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 "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :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( + status=status, + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + 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, + ) -> ApiResponse: + """ + Lists ExecutionInstance and returns headers from first page + + + :param "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + 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, + ) -> ApiResponse: + """ + Asynchronously lists ExecutionInstance and returns headers from first page + + + :param "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionPage: + """ + Retrieve a single page of ExecutionInstance records from the API. + Request is executed immediately + + :param status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :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 """ - :returns: The links - :rtype: unicode + data = values.of( + { + "status": status, + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionPage(self._version, response, solution=self._solution) + + async def page_async( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionPage: + """ + Asynchronously retrieve a single page of ExecutionInstance records from the API. + Request is executed immediately + + :param status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :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( + { + "status": status, + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :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: ApiResponse with ExecutionPage, status code, and headers + """ + data = values.of( + { + "status": status, + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ExecutionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + 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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :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: ApiResponse with ExecutionPage, status code, and headers + """ + data = values.of( + { + "status": status, + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - def fetch(self): + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ExecutionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ExecutionPage: """ - Fetch the ExecutionInstance + Retrieve a specific page of ExecutionInstance records from the API. + Request is executed immediately - :returns: The fetched ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionPage(self._version, response, solution=self._solution) - def delete(self): + async def get_page_async(self, target_url: str) -> ExecutionPage: """ - Deletes the ExecutionInstance + Asynchronously 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 = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionPage(self._version, response, solution=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 0abb988a52..d27773667f 100644 --- a/twilio/rest/studio/v2/flow/execution/execution_context.py +++ b/twilio/rest/studio/v2/flow/execution/execution_context.py @@ -1,267 +1,289 @@ -# 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.api_response import ApiResponse 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 ExecutionContextList(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 ExecutionContextList +from twilio.base.version import Version - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param execution_sid: The execution_sid - :returns: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextList - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextList - """ - super(ExecutionContextList, self).__init__(version) +class ExecutionContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionContext resource. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar flow_sid: The SID of the Flow. + :ivar execution_sid: The SID of the context's Execution resource. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } - # Path Solution - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, } + self._context: Optional[ExecutionContextContext] = None - def get(self): + @property + def _proxy(self) -> "ExecutionContextContext": """ - Constructs a ExecutionContextContext + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextContext - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextContext + :returns: ExecutionContextContext for this ExecutionContextInstance """ - return ExecutionContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - ) + if self._context is None: + self._context = ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + return self._context - def __call__(self): + def fetch(self) -> "ExecutionContextInstance": """ - Constructs a ExecutionContextContext + Fetch the ExecutionContextInstance - :returns: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextContext - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextContext - """ - return ExecutionContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - ) - def __repr__(self): + :returns: The fetched ExecutionContextInstance """ - Provide a friendly representation + return self._proxy.fetch() - :returns: Machine friendly representation - :rtype: str + async def fetch_async(self) -> "ExecutionContextInstance": """ - return '' + Asynchronous coroutine to fetch the ExecutionContextInstance -class ExecutionContextPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: The fetched ExecutionContextInstance + """ + return await self._proxy.fetch_async() - def __init__(self, version, response, solution): + def fetch_with_http_info(self) -> ApiResponse: """ - Initialize the ExecutionContextPage + Fetch the ExecutionContextInstance with HTTP info - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: The flow_sid - :param execution_sid: The execution_sid - :returns: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextPage - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextPage + :returns: ApiResponse with instance, status code, and headers """ - super(ExecutionContextPage, self).__init__(version, response) + return self._proxy.fetch_with_http_info() - # Path Solution - self._solution = solution - - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of ExecutionContextInstance + Asynchronous coroutine to fetch the ExecutionContextInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return ExecutionContextInstance( - self._version, - payload, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - ) + return await self._proxy.fetch_with_http_info_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 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): + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ Initialize the ExecutionContextContext - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param execution_sid: The execution_sid - - :returns: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextContext - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextContext + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution context to fetch. + :param execution_sid: The SID of the Execution context to fetch. """ - super(ExecutionContextContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, } - self._uri = '/Flows/{flow_sid}/Executions/{execution_sid}/Context'.format(**self._solution) + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Context".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ExecutionContextInstance: """ 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, _, _ = self._fetch() 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 + def fetch_with_http_info(self) -> ApiResponse: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Fetch the ExecutionContextInstance and return response metadata -class ExecutionContextInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __init__(self, version, payload, flow_sid, execution_sid): + async def _fetch_async(self) -> tuple: """ - Initialize the ExecutionContextInstance + Internal async helper for fetch operation - :returns: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextInstance + Returns: + tuple: (payload, status_code, headers) """ - 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'), - } + headers = values.of({}) - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: ExecutionContextContext for this ExecutionContextInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextContext + async def fetch_async(self) -> 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 + Asynchronous coroutine to fetch the ExecutionContextInstance - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + + :returns: The fetched ExecutionContextInstance """ - return self._properties['account_sid'] + payload, _, _ = await self._fetch_async() + return ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) - @property - def context(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: The context - :rtype: dict + Asynchronous coroutine to fetch the ExecutionContextInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['context'] + payload, status_code, headers = await self._fetch_async() + instance = ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def flow_sid(self): + def __repr__(self) -> str: """ - :returns: The flow_sid - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['flow_sid'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def execution_sid(self): + +class ExecutionContextList(ListResource): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ - :returns: The execution_sid - :rtype: unicode + Initialize the ExecutionContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution context to fetch. + :param execution_sid: The SID of the Execution context to fetch. + """ - return self._properties['execution_sid'] + super().__init__(version) - @property - def url(self): + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + + def get(self) -> ExecutionContextContext: """ - :returns: The url - :rtype: unicode + Constructs a ExecutionContextContext + """ - 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 58040ecd51..57c14a8ab6 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,745 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +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 type: The type of the widget that was executed. + :ivar date_created: 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.type: Optional[str] = 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.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") - def __init__(self, version, flow_sid, execution_sid): - """ - Initialize the ExecutionStepList + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "sid": sid or self.sid, + } - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param execution_sid: The execution_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'], limits['page_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): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of ExecutionStepInstance records from the API. - Request is executed immediately + Fetch the ExecutionStepInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ExecutionStepInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepPage + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionStepInstance with HTTP info - return ExecutionStepPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - 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 + return await self._proxy.fetch_with_http_info_async() - :returns: Page of ExecutionStepInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepPage + @property + def step_context(self) -> ExecutionStepContextList: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Access the step_context + """ + return self._proxy.step_context - return ExecutionStepPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a ExecutionStepContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The sid - :returns: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepContext - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepContext - """ - return ExecutionStepContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - sid=sid, - ) +class ExecutionStepContext(InstanceContext): - def __call__(self, sid): + def __init__(self, version: Version, flow_sid: str, execution_sid: str, sid: str): """ - Constructs a ExecutionStepContext - - :param sid: The sid + Initialize the ExecutionStepContext - :returns: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepContext - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepContext + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param sid: The SID of the ExecutionStep resource to fetch. """ - return ExecutionStepContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - sid=sid, + 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 ) - def __repr__(self): + self._step_context: Optional[ExecutionStepContextList] = None + + def _fetch(self) -> tuple: """ - Provide a friendly representation + Internal helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class ExecutionStepPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> ExecutionStepInstance: """ - Initialize the ExecutionStepPage + Fetch the ExecutionStepInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: The flow_sid - :param execution_sid: The execution_sid - :returns: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepPage - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepPage + :returns: The fetched ExecutionStepInstance """ - super(ExecutionStepPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = self._fetch() + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) - def get_instance(self, payload): + def fetch_with_http_info(self) -> ApiResponse: """ - Build an instance of ExecutionStepInstance + Fetch the ExecutionStepInstance and return response metadata - :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 + :returns: ApiResponse with instance, status code, and headers """ - return ExecutionStepInstance( + payload, status_code, headers = self._fetch() + instance = 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"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class ExecutionStepContext(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, flow_sid, execution_sid, sid): - """ - Initialize the ExecutionStepContext - - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param execution_sid: The execution_sid - :param sid: The sid + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepContext - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepContext + async def fetch_async(self) -> ExecutionStepInstance: """ - super(ExecutionStepContext, self).__init__(version) + Asynchronous coroutine to fetch the ExecutionStepInstance - # 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 - - def fetch(self): + :returns: The fetched ExecutionStepInstance """ - Fetch the ExecutionStepInstance + payload, _, _ = await self._fetch_async() + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) - :returns: The fetched ExecutionStepInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepInstance + async def fetch_with_http_info_async(self) -> ApiResponse: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronous coroutine to fetch the ExecutionStepInstance and return response metadata - return ExecutionStepInstance( + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ExecutionStepInstance( self._version, payload, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - sid=self._solution['sid'], + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def step_context(self): + def step_context(self) -> ExecutionStepContextList: """ Access the step_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 """ 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'], + self._solution["flow_sid"], + self._solution["execution_sid"], + self._solution["sid"], ) return self._step_context - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 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'), - } +class ExecutionStepPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ExecutionStepInstance: + """ + Build an instance of ExecutionStepInstance + + :param payload: Payload response from the API + """ + + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) - # Context - self._context = None + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ExecutionStepList(ListResource): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): + """ + Initialize the ExecutionStepList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Steps to read. + :param execution_sid: The SID of the Execution with the Steps to read. + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'flow_sid': flow_sid, - 'execution_sid': execution_sid, - 'sid': sid or self._properties['sid'], + "flow_sid": flow_sid, + "execution_sid": execution_sid, } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExecutionStepInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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: 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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = ExecutionStepContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_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[ExecutionStepInstance]: """ - :returns: The sid - :rtype: unicode + Asynchronously streams ExecutionStepInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The account_sid - :rtype: unicode + Streams ExecutionStepInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def flow_sid(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The flow_sid - :rtype: unicode + Asynchronously streams ExecutionStepInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['flow_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def execution_sid(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionStepInstance]: """ - :returns: The execution_sid - :rtype: unicode + Lists ExecutionStepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['execution_sid'] - @property - def name(self): + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionStepInstance]: """ - :returns: The name - :rtype: unicode + Asynchronously lists ExecutionStepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['name'] - @property - def context(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The context - :rtype: dict + Lists ExecutionStepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['context'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def transitioned_from(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The transitioned_from - :rtype: unicode + Asynchronously lists ExecutionStepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['transitioned_from'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def transitioned_to(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, + ) -> ExecutionStepPage: + """ + Retrieve a single page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionStepInstance """ - :returns: The transitioned_to - :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 ExecutionStepPage(self._version, response, solution=self._solution) + + async def 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: """ - return self._properties['transitioned_to'] + Asynchronously retrieve a single page of ExecutionStepInstance 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 ExecutionStepInstance """ - :returns: The date_created - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionStepPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_created'] + Retrieve a single page with response metadata - @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: ApiResponse with ExecutionStepPage, status code, and headers """ - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ExecutionStepPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with ExecutionStepPage, status code, and headers """ - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ExecutionStepPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ExecutionStepPage: """ - return self._properties['url'] + Retrieve a specific page of ExecutionStepInstance 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 ExecutionStepInstance """ - :returns: The links - :rtype: unicode + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionStepPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ExecutionStepPage: """ - return self._properties['links'] + Asynchronously retrieve a specific page of ExecutionStepInstance 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 ExecutionStepInstance """ - Fetch the ExecutionStepInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionStepPage(self._version, response, solution=self._solution) - :returns: The fetched ExecutionStepInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepInstance + def get(self, sid: str) -> ExecutionStepContext: """ - return self._proxy.fetch() + Constructs a ExecutionStepContext - @property - def step_context(self): + :param sid: The SID of the ExecutionStep resource to fetch. """ - Access the step_context + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=sid, + ) - :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 __call__(self, sid: str) -> ExecutionStepContext: """ - return self._proxy.step_context + Constructs a ExecutionStepContext + + :param sid: The SID of the ExecutionStep resource to fetch. + """ + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 a4a7083df5..af826482f5 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,308 @@ -# 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.api_response import ApiResponse 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 ExecutionStepContextList(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, step_sid): - """ - Initialize the ExecutionStepContextList +from twilio.base.version import Version - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param execution_sid: The execution_sid - :param step_sid: The step_sid - :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 - """ - super(ExecutionStepContextList, self).__init__(version) +class ExecutionStepContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStepContext resource. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar execution_sid: The SID of the context's Execution resource. + :ivar flow_sid: The SID of the Flow. + :ivar step_sid: The SID of the Step that the context is associated with. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + step_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.step_sid: Optional[str] = payload.get("step_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } - # Path Solution - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, 'step_sid': step_sid, } + self._context: Optional[ExecutionStepContextContext] = None - def get(self): + @property + def _proxy(self) -> "ExecutionStepContextContext": """ - Constructs a ExecutionStepContextContext + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: 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: ExecutionStepContextContext for this ExecutionStepContextInstance """ - return ExecutionStepContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - step_sid=self._solution['step_sid'], - ) + if self._context is None: + self._context = ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + return self._context - def __call__(self): + def fetch(self) -> "ExecutionStepContextInstance": """ - Constructs a ExecutionStepContextContext + Fetch the ExecutionStepContextInstance - :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 - """ - 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): + :returns: The fetched ExecutionStepContextInstance """ - Provide a friendly representation + return self._proxy.fetch() - :returns: Machine friendly representation - :rtype: str + async def fetch_async(self) -> "ExecutionStepContextInstance": """ - return '' + Asynchronous coroutine to fetch the ExecutionStepContextInstance -class ExecutionStepContextPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: The fetched ExecutionStepContextInstance + """ + return await self._proxy.fetch_async() - def __init__(self, version, response, solution): + def fetch_with_http_info(self) -> ApiResponse: """ - Initialize the ExecutionStepContextPage + Fetch the ExecutionStepContextInstance with HTTP info - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: The flow_sid - :param execution_sid: The execution_sid - :param step_sid: The step_sid - :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 + :returns: ApiResponse with instance, status code, and headers """ - super(ExecutionStepContextPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info() - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of ExecutionStepContextInstance + Asynchronous coroutine to fetch the ExecutionStepContextInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return ExecutionStepContextInstance( - self._version, - payload, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - step_sid=self._solution['step_sid'], - ) + return await self._proxy.fetch_with_http_info_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 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): + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): """ Initialize the ExecutionStepContextContext - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param execution_sid: The execution_sid - :param step_sid: The 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 + :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(ExecutionStepContextContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, 'step_sid': step_sid, } - self._uri = '/Flows/{flow_sid}/Executions/{execution_sid}/Steps/{step_sid}/Context'.format(**self._solution) + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps/{step_sid}/Context".format( + **self._solution + ) - def fetch(self): + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ExecutionStepContextInstance: """ 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, _, _ = self._fetch() 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): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + def fetch_with_http_info(self) -> ApiResponse: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Fetch the ExecutionStepContextInstance and return response metadata -class ExecutionStepContextInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __init__(self, version, payload, flow_sid, execution_sid, step_sid): + async def _fetch_async(self) -> tuple: """ - Initialize the ExecutionStepContextInstance + Internal async helper for fetch operation - :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: + tuple: (payload, status_code, headers) """ - 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'), - } + headers = values.of({}) - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, 'step_sid': step_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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: ExecutionStepContextContext for this ExecutionStepContextInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext + async def fetch_async(self) -> 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 + Asynchronous coroutine to fetch the ExecutionStepContextInstance - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def context(self): - """ - :returns: The context - :rtype: dict + :returns: The fetched ExecutionStepContextInstance """ - return self._properties['context'] + payload, _, _ = await self._fetch_async() + return ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) - @property - def execution_sid(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: The execution_sid - :rtype: unicode + Asynchronous coroutine to fetch the ExecutionStepContextInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['execution_sid'] + payload, status_code, headers = await self._fetch_async() + instance = ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def flow_sid(self): + def __repr__(self) -> str: """ - :returns: The flow_sid - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['flow_sid'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def step_sid(self): + +class ExecutionStepContextList(ListResource): + + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): """ - :returns: The step_sid - :rtype: unicode + Initialize the ExecutionStepContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param step_sid: The SID of the Step to fetch. + """ - return self._properties['step_sid'] + super().__init__(version) - @property - def url(self): + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + + def get(self) -> ExecutionStepContextContext: """ - :returns: The url - :rtype: unicode + Constructs a ExecutionStepContextContext + """ - 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 42fe2bf2aa..046e08d7c6 100644 --- a/twilio/rest/studio/v2/flow/flow_revision.py +++ b/twilio/rest/studio/v2/flow/flow_revision.py @@ -1,402 +1,696 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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" - :param Version version: Version that contains the resource - :param sid: The unique string that identifies 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 author_sid: The SID of the User that created or last updated the Flow. + :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.author_sid: Optional[str] = payload.get("author_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") - :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionList - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionList - """ - super(FlowRevisionList, self).__init__(version) + self._solution = { + "sid": sid, + "revision": revision or self.revision, + } - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Flows/{sid}/Revisions'.format(**self._solution) + self._context: Optional[FlowRevisionContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "FlowRevisionContext": """ - 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. + 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: 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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance] + def fetch(self) -> "FlowRevisionInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the FlowRevisionInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched FlowRevisionInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the FlowRevisionInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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 """ - 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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of FlowRevisionInstance records from the API. - Request is executed immediately + Fetch the FlowRevisionInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowRevisionInstance with HTTP info - return FlowRevisionPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of FlowRevisionInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of FlowRevisionInstance - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionPage + :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 FlowRevisionPage(self._version, response, self._solution) +class FlowRevisionContext(InstanceContext): - def get(self, revision): + def __init__(self, version: Version, sid: str, revision: str): """ - Constructs a FlowRevisionContext + Initialize the FlowRevisionContext - :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. + :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision`. + """ + super().__init__(version) - :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext + # Path Solution + self._solution = { + "sid": sid, + "revision": revision, + } + self._uri = "/Flows/{sid}/Revisions/{revision}".format(**self._solution) + + def _fetch(self) -> tuple: """ - return FlowRevisionContext(self._version, sid=self._solution['sid'], revision=revision, ) + Internal helper for fetch operation - def __call__(self, revision): + Returns: + tuple: (payload, status_code, headers) """ - Constructs a FlowRevisionContext - :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision` + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + 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 + def fetch(self) -> FlowRevisionInstance: """ - return FlowRevisionContext(self._version, sid=self._solution['sid'], revision=revision, ) + Fetch the FlowRevisionInstance + - def __repr__(self): + :returns: The fetched FlowRevisionInstance """ - Provide a friendly representation + payload, _, _ = self._fetch() + return FlowRevisionInstance( + self._version, + payload, + sid=self._solution["sid"], + revision=self._solution["revision"], + ) - :returns: Machine friendly representation - :rtype: str + def fetch_with_http_info(self) -> ApiResponse: """ - return '' + Fetch the FlowRevisionInstance and return response metadata -class FlowRevisionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FlowRevisionInstance( + self._version, + payload, + sid=self._solution["sid"], + revision=self._solution["revision"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - def __init__(self, version, response, solution): + Returns: + tuple: (payload, status_code, headers) """ - 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 + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionPage - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionPage + async def fetch_async(self) -> FlowRevisionInstance: """ - super(FlowRevisionPage, self).__init__(version, response) + Asynchronous coroutine to fetch the FlowRevisionInstance - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: The fetched FlowRevisionInstance """ - Build an instance of FlowRevisionInstance + payload, _, _ = await self._fetch_async() + return FlowRevisionInstance( + self._version, + payload, + sid=self._solution["sid"], + revision=self._solution["revision"], + ) - :param dict payload: Payload response from the API + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowRevisionInstance and return response metadata - :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance + + :returns: ApiResponse with instance, status code, and headers """ - return FlowRevisionInstance(self._version, payload, sid=self._solution['sid'], ) + payload, status_code, headers = await self._fetch_async() + instance = FlowRevisionInstance( + self._version, + payload, + sid=self._solution["sid"], + revision=self._solution["revision"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 FlowRevisionContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class FlowRevisionPage(Page): - def __init__(self, version, sid, revision): + def get_instance(self, payload: Dict[str, Any]) -> FlowRevisionInstance: + """ + Build an instance of FlowRevisionInstance + + :param payload: Payload response from the API """ - Initialize the FlowRevisionContext - :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` + return FlowRevisionInstance(self._version, payload, sid=self._solution["sid"]) - :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext + def __repr__(self) -> str: """ - super(FlowRevisionContext, self).__init__(version) + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" - # Path Solution - self._solution = {'sid': sid, 'revision': revision, } - self._uri = '/Flows/{sid}/Revisions/{revision}'.format(**self._solution) - def fetch(self): +class FlowRevisionList(ListResource): + + def __init__(self, version: Version, sid: str): """ - Fetch the FlowRevisionInstance + Initialize the FlowRevisionList + + :param version: Version that contains the resource + :param sid: The SID of the Flow resource to fetch. - :returns: The fetched FlowRevisionInstance - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + super().__init__(version) - return FlowRevisionInstance( - self._version, - payload, - sid=self._solution['sid'], - revision=self._solution['revision'], - ) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Flows/{sid}/Revisions".format(**self._solution) - def __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FlowRevisionInstance]: """ - Provide a friendly representation + 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 + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 FlowRevisionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FlowRevisionInstance]: + """ + Asynchronously streams FlowRevisionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - class Status(object): - DRAFT = "draft" - PUBLISHED = "published" + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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, 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'), - } + :returns: Generator that 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 = {'sid': sid, 'revision': revision or self._properties['revision'], } + return self._version.stream_async(page, limits["limit"]) - @property - def _proxy(self): + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Streams FlowRevisionInstance and returns headers from first page - :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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - if self._context is None: - self._context = FlowRevisionContext( - self._version, - sid=self._solution['sid'], - revision=self._solution['revision'], - ) - return self._context + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def sid(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Asynchronously streams FlowRevisionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['sid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def account_sid(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowRevisionInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Lists FlowRevisionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['account_sid'] - @property - def friendly_name(self): + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowRevisionInstance]: """ - :returns: The string that you assigned to describe the Flow - :rtype: unicode + Asynchronously lists FlowRevisionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['friendly_name'] - @property - def definition(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: JSON representation of flow definition - :rtype: dict + Lists FlowRevisionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['definition'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def status(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The status of the Flow - :rtype: FlowRevisionInstance.Status + Asynchronously lists FlowRevisionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['status'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def revision(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, + ) -> FlowRevisionPage: """ - :returns: The latest revision number of the Flow's definition - :rtype: unicode + Retrieve a single page of FlowRevisionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlowRevisionInstance """ - return self._properties['revision'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def commit_message(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 FlowRevisionPage(self._version, response, solution=self._solution) + + async def 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 + Asynchronously retrieve a single page of FlowRevisionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlowRevisionInstance """ - return self._properties['commit_message'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def valid(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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: Boolean if the flow definition is valid - :rtype: bool + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FlowRevisionPage, status code, and headers """ - return self._properties['valid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def errors(self): + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FlowRevisionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: List of error in the flow definition - :rtype: dict + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FlowRevisionPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FlowRevisionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..c030529dde --- /dev/null +++ b/twilio/rest/studio/v2/flow/flow_test_user.py @@ -0,0 +1,403 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowTestUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowTestUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info(self, test_users: List[str]) -> ApiResponse: + """ + Update the FlowTestUserInstance with HTTP info + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + test_users=test_users, + ) + + async def update_with_http_info_async(self, test_users: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the FlowTestUserInstance with HTTP info + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> FlowTestUserInstance: + """ + Fetch the FlowTestUserInstance + + + :returns: The fetched FlowTestUserInstance + """ + payload, _, _ = self._fetch() + return FlowTestUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowTestUserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FlowTestUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> FlowTestUserInstance: + """ + Asynchronous coroutine to fetch the FlowTestUserInstance + + + :returns: The fetched FlowTestUserInstance + """ + payload, _, _ = await self._fetch_async() + return FlowTestUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowTestUserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FlowTestUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, test_users: List[str]) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(test_users=test_users) + return FlowTestUserInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info(self, test_users: List[str]) -> ApiResponse: + """ + Update the FlowTestUserInstance and return response metadata + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(test_users=test_users) + instance = FlowTestUserInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, test_users: List[str]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(test_users=test_users) + return FlowTestUserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async(self, test_users: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the FlowTestUserInstance and return response metadata + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(test_users=test_users) + instance = FlowTestUserInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..390ad74ca3 100644 --- a/twilio/rest/studio/v2/flow_validate.py +++ b/twilio/rest/studio/v2/flow_validate.py @@ -1,148 +1,234 @@ -# 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_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.page import Page - + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ -class FlowValidateList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + Twilio - Studio + This is the public Twilio REST API. - def __init__(self, version): - """ - Initialize the FlowValidateList + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" - :param Version version: Version that contains the resource +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse - :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. """ - def __init__(self, version, response, solution): - """ - Initialize the FlowValidatePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API +class FlowValidateList(ListResource): - :returns: twilio.rest.studio.v2.flow_validate.FlowValidatePage - :rtype: twilio.rest.studio.v2.flow_validate.FlowValidatePage + def __init__(self, version: Version): """ - super(FlowValidatePage, self).__init__(version, response) + Initialize the FlowValidateList - # Path Solution - self._solution = solution + :param version: Version that contains the resource - def get_instance(self, payload): """ - Build an instance of FlowValidateInstance + super().__init__(version) - :param dict payload: Payload response from the API + self._uri = "/Flows/Validate" - :returns: twilio.rest.studio.v2.flow_validate.FlowValidateInstance - :rtype: twilio.rest.studio.v2.flow_validate.FlowValidateInstance + def _update( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> tuple: """ - return FlowValidateInstance(self._version, payload, ) + Internal helper for update operation - def __repr__(self): + Returns: + tuple: (payload, status_code, headers) """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - return '' + 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" -class FlowValidateInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" - class Status(object): - DRAFT = "draft" - PUBLISHED = "published" - - def __init__(self, version, payload): - """ - Initialize the FlowValidateInstance + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.studio.v2.flow_validate.FlowValidateInstance - :rtype: twilio.rest.studio.v2.flow_validate.FlowValidateInstance + def update( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowValidateInstance: """ - super(FlowValidateInstance, self).__init__(version) - - # Marshaled Properties - self._properties = {'valid': payload.get('valid'), } + Update the FlowValidateInstance - # Context - self._context = None - self._solution = {} + :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 valid(self): - """ - :returns: The valid - :rtype: bool + :returns: The updated FlowValidateInstance """ - return self._properties['valid'] + payload, _, _ = self._update( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + ) + return FlowValidateInstance(self._version, payload) + + def update_with_http_info( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the FlowValidateInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + ) + instance = FlowValidateInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowValidateInstance: + """ + Asynchronously update the FlowValidateInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. - def __repr__(self): + :returns: The updated FlowValidateInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + ) + return FlowValidateInstance(self._version, payload) + + async def update_with_http_info_async( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously update the FlowValidateInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + ) + instance = FlowValidateInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 d5063ca8af..98928dad6a 100644 --- a/twilio/rest/supersim/__init__.py +++ b/twilio/rest/supersim/__init__.py @@ -1,74 +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) +class Supersim(SupersimBase): + @property + def esim_profiles(self) -> EsimProfileList: + warn( + "esim_profiles is deprecated. Use v1.esim_profiles instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.esim_profiles - self.base_url = 'https://supersim.twilio.com' + @property + def fleets(self) -> FleetList: + warn( + "fleets is deprecated. Use v1.fleets instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.fleets - # Versions - self._v1 = None + @property + def ip_commands(self) -> IpCommandList: + warn( + "ip_commands is deprecated. Use v1.ip_commands instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.ip_commands @property - def 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 networks(self) -> NetworkList: + warn( + "networks is deprecated. Use v1.networks instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.networks @property - def commands(self): - """ - :rtype: twilio.rest.supersim.v1.command.CommandList - """ - return self.v1.commands + 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 fleets(self): - """ - :rtype: twilio.rest.supersim.v1.fleet.FleetList - """ - return self.v1.fleets + def settings_updates(self) -> SettingsUpdateList: + warn( + "settings_updates is deprecated. Use v1.settings_updates instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.settings_updates @property - def sims(self): - """ - :rtype: twilio.rest.supersim.v1.sim.SimList - """ + def sims(self) -> SimList: + warn( + "sims is deprecated. Use v1.sims instead.", DeprecationWarning, stacklevel=2 + ) return self.v1.sims @property - def usage_records(self): - """ - :rtype: twilio.rest.supersim.v1.usage_record.UsageRecordList - """ - return self.v1.usage_records - - def __repr__(self): - """ - Provide a friendly representation + 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 e535648946..2336da2616 100644 --- a/twilio/rest/supersim/v1/__init__.py +++ b/twilio/rest/supersim/v1/__init__.py @@ -1,75 +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 + :param domain: The Twilio.supersim domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._commands = None - self._fleets = None - self._sims = None - self._usage_records = None + 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 sims(self): - """ - :rtype: twilio.rest.supersim.v1.sim.SimList - """ + def ip_commands(self) -> IpCommandList: + if self._ip_commands is None: + self._ip_commands = IpCommandList(self) + return self._ip_commands + + @property + def networks(self) -> NetworkList: + if self._networks is None: + self._networks = NetworkList(self) + return self._networks + + @property + def network_access_profiles(self) -> NetworkAccessProfileList: + if self._network_access_profiles is None: + self._network_access_profiles = NetworkAccessProfileList(self) + return self._network_access_profiles + + @property + def settings_updates(self) -> SettingsUpdateList: + if self._settings_updates is None: + self._settings_updates = SettingsUpdateList(self) + return self._settings_updates + + @property + def sims(self) -> SimList: if self._sims is None: self._sims = SimList(self) return self._sims @property - def 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 caa4e274e2..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'], limits['page_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..f60d8f11d0 --- /dev/null +++ b/twilio/rest/supersim/v1/esim_profile.py @@ -0,0 +1,949 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EsimProfileInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EsimProfileInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EsimProfileInstance: + """ + Fetch the EsimProfileInstance + + + :returns: The fetched EsimProfileInstance + """ + payload, _, _ = self._fetch() + return EsimProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EsimProfileInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EsimProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> EsimProfileInstance: + """ + Asynchronous coroutine to fetch the EsimProfileInstance + + + :returns: The fetched EsimProfileInstance + """ + payload, _, _ = await self._fetch_async() + return EsimProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EsimProfileInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EsimProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + callback_url=callback_url, + callback_method=callback_method, + generate_matching_id=generate_matching_id, + eid=eid, + ) + return EsimProfileInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the EsimProfileInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + callback_url=callback_url, + callback_method=callback_method, + generate_matching_id=generate_matching_id, + eid=eid, + ) + instance = EsimProfileInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + callback_url=callback_url, + callback_method=callback_method, + generate_matching_id=generate_matching_id, + eid=eid, + ) + return EsimProfileInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the EsimProfileInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + callback_url=callback_url, + callback_method=callback_method, + generate_matching_id=generate_matching_id, + eid=eid, + ) + instance = EsimProfileInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams EsimProfileInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + eid=eid, sim_sid=sim_sid, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams EsimProfileInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + eid=eid, sim_sid=sim_sid, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists EsimProfileInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + eid=eid, + sim_sid=sim_sid, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists EsimProfileInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + eid=eid, + sim_sid=sim_sid, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with EsimProfilePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EsimProfilePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with EsimProfilePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EsimProfilePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 1f2492ca0c..7f17059350 100644 --- a/twilio/rest/supersim/v1/fleet.py +++ b/twilio/rest/supersim/v1/fleet.py @@ -1,437 +1,1312 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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. """ +class FleetInstance(InstanceResource): - def __init__(self, version): + class DataMetering(object): + PAYG = "payg" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Fleet resource. + :ivar sid: The unique string that we created to identify the Fleet resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Fleet resource. + :ivar data_enabled: Defines whether SIMs in the Fleet are capable of using 2G/3G/4G/LTE/CAT-M data connectivity. Defaults to `true`. + :ivar data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 250MB. + :ivar data_metering: + :ivar sms_commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `false`. + :ivar sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :ivar sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :ivar network_access_profile_sid: The SID of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :ivar ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :ivar ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.data_enabled: Optional[bool] = payload.get("data_enabled") + self.data_limit: Optional[int] = deserialize.integer(payload.get("data_limit")) + self.data_metering: Optional["FleetInstance.DataMetering"] = payload.get( + "data_metering" + ) + self.sms_commands_enabled: Optional[bool] = payload.get("sms_commands_enabled") + self.sms_commands_url: Optional[str] = payload.get("sms_commands_url") + self.sms_commands_method: Optional[str] = payload.get("sms_commands_method") + self.network_access_profile_sid: Optional[str] = payload.get( + "network_access_profile_sid" + ) + self.ip_commands_url: Optional[str] = payload.get("ip_commands_url") + self.ip_commands_method: Optional[str] = payload.get("ip_commands_method") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[FleetContext] = None + + @property + def _proxy(self) -> "FleetContext": """ - Initialize the FleetList + 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: FleetContext for this FleetInstance + """ + if self._context is None: + self._context = FleetContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.supersim.v1.fleet.FleetList - :rtype: twilio.rest.supersim.v1.fleet.FleetList + def fetch(self) -> "FleetInstance": """ - super(FleetList, self).__init__(version) + Fetch the FleetInstance - # Path Solution - self._solution = {} - self._uri = '/Fleets'.format(**self._solution) - def create(self, unique_name=values.unset, data_enabled=values.unset, - commands_enabled=values.unset, commands_url=values.unset, - commands_method=values.unset): + :returns: The fetched FleetInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FleetInstance": """ - Create the FleetInstance + Asynchronous coroutine to fetch the FleetInstance - :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 bool commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving Commands via SMS - :param unicode commands_url: The URL that will receive a webhook when a SIM in the Fleet originates a machine-to-machine Command - :param unicode commands_method: A string representing the HTTP method to use when making a request to `commands_url` - :returns: The created FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetInstance + :returns: The fetched FleetInstance """ - data = values.of({ - 'UniqueName': unique_name, - 'DataEnabled': data_enabled, - 'CommandsEnabled': commands_enabled, - 'CommandsUrl': commands_url, - 'CommandsMethod': commands_method, - }) + return await self._proxy.fetch_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FleetInstance with HTTP info - return FleetInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with instance, status code, and headers """ - 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. + return self._proxy.fetch_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FleetInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.supersim.v1.fleet.FleetInstance] + + :returns: ApiResponse with instance, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.fetch_with_http_info_async() - page = self.page(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'], limits['page_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, 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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(limit=limit, page_size=page_size, )) + return await self._proxy.update_async( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the FleetInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FleetInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) + + def __repr__(self) -> str: """ - Retrieve a single page of FleetInstance 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 str page_token: PageToken provided by the API - :param int page_number: 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.supersim.v1.fleet.FleetPage +class FleetContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the FleetContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :param version: Version that contains the resource + :param sid: The SID of the Fleet resource to update. + """ + 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_page(self, target_url): + def _fetch(self) -> tuple: """ - Retrieve a specific page of FleetInstance records from the API. - Request is executed immediately + Internal helper for fetch operation - :param str target_url: API-generated URL for the requested results page + Returns: + tuple: (payload, status_code, headers) + """ - :returns: Page of FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetPage + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> FleetInstance: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Fetch the FleetInstance + + + :returns: The fetched FleetInstance + """ + payload, _, _ = self._fetch() + return FleetInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return FleetPage(self._version, response, self._solution) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FleetInstance and return response metadata + - def get(self, sid): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a FleetContext + payload, status_code, headers = self._fetch() + instance = FleetInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param sid: The SID that identifies the resource to fetch + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: twilio.rest.supersim.v1.fleet.FleetContext - :rtype: twilio.rest.supersim.v1.fleet.FleetContext + Returns: + tuple: (payload, status_code, headers) """ - return FleetContext(self._version, sid=sid, ) - def __call__(self, sid): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> FleetInstance: """ - Constructs a FleetContext + Asynchronous coroutine to 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, ) + payload, _, _ = await self._fetch_async() + return FleetInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the FleetInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - return '' + payload, status_code, headers = await self._fetch_async() + instance = FleetInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" -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): + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - Initialize the FleetPage + Update the FleetInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API + :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: twilio.rest.supersim.v1.fleet.FleetPage - :rtype: twilio.rest.supersim.v1.fleet.FleetPage + :returns: The updated FleetInstance """ - super(FleetPage, self).__init__(version, response) + payload, _, _ = self._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, + ) + return FleetInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the FleetInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = FleetInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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({}) - # Path Solution - self._solution = solution + headers["Content-Type"] = "application/x-www-form-urlencoded" - def get_instance(self, payload): - """ - Build an instance of FleetInstance + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :param dict payload: Payload response from the API + 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: twilio.rest.supersim.v1.fleet.FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetInstance + :returns: The updated FleetInstance """ - return FleetInstance(self._version, payload, ) + payload, _, _ = await self._update_async( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) + return FleetInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FleetInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) + instance = FleetInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 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 - - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch + Build an instance of FleetInstance - :returns: twilio.rest.supersim.v1.fleet.FleetContext - :rtype: twilio.rest.supersim.v1.fleet.FleetContext + :param payload: Payload response from the API """ - super(FleetContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Fleets/{sid}'.format(**self._solution) + return FleetInstance(self._version, payload) - def fetch(self): + def __repr__(self) -> str: """ - Fetch the FleetInstance + Provide a friendly representation - :returns: The fetched FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetInstance + :returns: Machine friendly representation """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + return "" - return FleetInstance(self._version, payload, sid=self._solution['sid'], ) - def update(self, unique_name=values.unset): +class FleetList(ListResource): + + def __init__(self, version: Version): """ - Update the FleetInstance + Initialize the FleetList - :param unicode unique_name: An application-defined string that uniquely identifies the resource + :param version: Version that contains the resource - :returns: The updated FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetInstance """ - data = values.of({'UniqueName': unique_name, }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + super().__init__(version) - return FleetInstance(self._version, payload, sid=self._solution['sid'], ) + self._uri = "/Fleets" - def __repr__(self): + 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, + ) -> tuple: """ - Provide a friendly representation + Internal helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - 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): + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - Initialize the FleetInstance + Create the FleetInstance - :returns: twilio.rest.supersim.v1.fleet.FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.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 """ - super(FleetInstance, self).__init__(version) + payload, _, _ = self._create( + network_access_profile=network_access_profile, + unique_name=unique_name, + data_enabled=data_enabled, + data_limit=data_limit, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_enabled=sms_commands_enabled, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + ) + return FleetInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the FleetInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + network_access_profile=network_access_profile, + unique_name=unique_name, + data_enabled=data_enabled, + data_limit=data_limit, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_enabled=sms_commands_enabled, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + ) + instance = FleetInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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"}) - # 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_metering': payload.get('data_metering'), - 'commands_enabled': payload.get('commands_enabled'), - 'commands_url': payload.get('commands_url'), - 'commands_method': payload.get('commands_method'), - } + 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 + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: FleetContext for this FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetContext + 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 """ - if self._context is None: - self._context = FleetContext(self._version, sid=self._solution['sid'], ) - return self._context + payload, _, _ = await self._create_async( + network_access_profile=network_access_profile, + unique_name=unique_name, + data_enabled=data_enabled, + data_limit=data_limit, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_enabled=sms_commands_enabled, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + ) + return FleetInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the FleetInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + network_access_profile=network_access_profile, + unique_name=unique_name, + data_enabled=data_enabled, + data_limit=data_limit, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_enabled=sms_commands_enabled, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + ) + instance = FleetInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def account_sid(self): + def stream( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FleetInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Streams FleetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FleetInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Asynchronously streams FleetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['sid'] + 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 unique_name(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + Streams FleetInstance and returns headers from first page + + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['unique_name'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + network_access_profile=network_access_profile, page_size=limits["page_size"] + ) - @property - def date_created(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Asynchronously streams FleetInstance and returns headers from first page + + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + network_access_profile=network_access_profile, page_size=limits["page_size"] + ) - @property - def date_updated(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FleetInstance]: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Lists FleetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['date_updated'] - @property - def url(self): + return list( + self.stream( + network_access_profile=network_access_profile, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FleetInstance]: """ - :returns: The absolute URL of the Fleet resource - :rtype: unicode + Asynchronously lists FleetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + network_access_profile=network_access_profile, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists FleetInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + network_access_profile=network_access_profile, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['url'] + Asynchronously lists FleetInstance and returns headers from first page - @property - def data_enabled(self): + + :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: ApiResponse with list of instances, status code, and headers """ - :returns: Defines whether SIMs in the Fleet are capable of using data connectivity - :rtype: bool + generator, status_code, headers = await self.stream_with_http_info_async( + network_access_profile=network_access_profile, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['data_enabled'] + Retrieve a single page of FleetInstance records from the API. + Request is executed immediately - @property - def data_metering(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 model by which a SIM is metered and billed - :rtype: FleetInstance.DataMetering + 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['data_metering'] + Asynchronously retrieve a single page of FleetInstance records from the API. + Request is executed immediately - @property - def commands_enabled(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: Defines whether SIMs in the Fleet are capable of sending and receiving Commands via SMS - :rtype: bool + 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 page_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['commands_enabled'] + Retrieve a single page with response metadata - @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: ApiResponse with FleetPage, status code, and headers """ - :returns: The URL that will receive a webhook when a SIM in the Fleet originates a machine-to-machine Command - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FleetPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with FleetPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FleetPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> FleetPage: """ - return self._properties['commands_url'] + Retrieve a specific page of FleetInstance records from the API. + Request is executed immediately - @property - def commands_method(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of FleetInstance """ - :returns: A string representing the HTTP method to use when making a request to `commands_url` - :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['commands_method'] + Asynchronously retrieve a specific page of FleetInstance 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 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): + :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 + 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, ) + 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..2af10f7bfb --- /dev/null +++ b/twilio/rest/supersim/v1/ip_command.py @@ -0,0 +1,1039 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpCommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpCommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpCommandInstance: + """ + Fetch the IpCommandInstance + + + :returns: The fetched IpCommandInstance + """ + payload, _, _ = self._fetch() + return IpCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpCommandInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = IpCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> IpCommandInstance: + """ + Asynchronous coroutine to fetch the IpCommandInstance + + + :returns: The fetched IpCommandInstance + """ + payload, _, _ = await self._fetch_async() + return IpCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpCommandInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = IpCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + sim=sim, + payload=payload, + device_port=device_port, + payload_type=payload_type, + callback_url=callback_url, + callback_method=callback_method, + ) + return IpCommandInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the IpCommandInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + sim=sim, + payload=payload, + device_port=device_port, + payload_type=payload_type, + callback_url=callback_url, + callback_method=callback_method, + ) + instance = IpCommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + sim=sim, + payload=payload, + device_port=device_port, + payload_type=payload_type, + callback_url=callback_url, + callback_method=callback_method, + ) + return IpCommandInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the IpCommandInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + sim=sim, + payload=payload, + device_port=device_port, + payload_type=payload_type, + callback_url=callback_url, + callback_method=callback_method, + ) + instance = IpCommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams IpCommandInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams IpCommandInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists IpCommandInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists IpCommandInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with IpCommandPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IpCommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with IpCommandPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IpCommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> IpCommandPage: + """ + Retrieve a specific page of IpCommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpCommandInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IpCommandPage(self._version, response) + + async def get_page_async(self, target_url: str) -> IpCommandPage: + """ + Asynchronously retrieve a specific page of IpCommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpCommandInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpCommandPage(self._version, response) + + def get(self, sid: str) -> IpCommandContext: + """ + Constructs a IpCommandContext + + :param sid: The SID of the IP Command resource to fetch. + """ + return IpCommandContext(self._version, sid=sid) + + def __call__(self, sid: str) -> IpCommandContext: + """ + Constructs a IpCommandContext + + :param sid: The SID of the IP Command resource to fetch. + """ + return IpCommandContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/supersim/v1/network.py b/twilio/rest/supersim/v1/network.py new file mode 100644 index 0000000000..c89787b807 --- /dev/null +++ b/twilio/rest/supersim/v1/network.py @@ -0,0 +1,751 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class NetworkInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Network resource. + :ivar friendly_name: A human readable identifier of this resource. + :ivar url: The absolute URL of the Network resource. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resource. + :ivar identifiers: Array of objects identifying the [MCC-MNCs](https://en.wikipedia.org/wiki/Mobile_country_code) that are included in the Network resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.url: Optional[str] = payload.get("url") + self.iso_country: Optional[str] = payload.get("iso_country") + self.identifiers: Optional[List[Dict[str, object]]] = payload.get("identifiers") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[NetworkContext] = None + + @property + def _proxy(self) -> "NetworkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NetworkContext for this NetworkInstance + """ + if self._context is None: + self._context = NetworkContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "NetworkInstance": + """ + Fetch the NetworkInstance + + + :returns: The fetched NetworkInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NetworkInstance": + """ + Asynchronous coroutine to fetch the NetworkInstance + + + :returns: The fetched NetworkInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NetworkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NetworkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NetworkContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the NetworkContext + + :param version: Version that contains the resource + :param sid: The SID of the Network resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Networks/{sid}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> NetworkInstance: + """ + Fetch the NetworkInstance + + + :returns: The fetched NetworkInstance + """ + payload, _, _ = self._fetch() + return NetworkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NetworkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = NetworkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> NetworkInstance: + """ + Asynchronous coroutine to fetch the NetworkInstance + + + :returns: The fetched NetworkInstance + """ + payload, _, _ = await self._fetch_async() + return NetworkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NetworkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = NetworkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 NetworkPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> NetworkInstance: + """ + Build an instance of NetworkInstance + + :param payload: Payload response from the API + """ + + return NetworkInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class NetworkList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the NetworkList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Networks" + + def stream( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NetworkInstance]: + """ + Streams NetworkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + iso_country=iso_country, mcc=mcc, mnc=mnc, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NetworkInstance]: + """ + Asynchronously streams NetworkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + iso_country=iso_country, mcc=mcc, mnc=mnc, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams NetworkInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + iso_country=iso_country, mcc=mcc, mnc=mnc, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams NetworkInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + iso_country=iso_country, mcc=mcc, mnc=mnc, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkInstance]: + """ + Lists NetworkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + iso_country=iso_country, + mcc=mcc, + mnc=mnc, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkInstance]: + """ + Asynchronously lists NetworkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + iso_country=iso_country, + mcc=mcc, + mnc=mnc, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists NetworkInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + iso_country=iso_country, + mcc=mcc, + mnc=mnc, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists NetworkInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + iso_country=iso_country, + mcc=mcc, + mnc=mnc, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkPage: + """ + Retrieve a single page of NetworkInstance records from the API. + Request is executed immediately + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkInstance + """ + data = values.of( + { + "IsoCountry": iso_country, + "Mcc": mcc, + "Mnc": mnc, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkPage(self._version, response) + + async def page_async( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkPage: + """ + Asynchronously retrieve a single page of NetworkInstance records from the API. + Request is executed immediately + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkInstance + """ + data = values.of( + { + "IsoCountry": iso_country, + "Mcc": mcc, + "Mnc": mnc, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkPage(self._version, response) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with NetworkPage, status code, and headers + """ + data = values.of( + { + "IsoCountry": iso_country, + "Mcc": mcc, + "Mnc": mnc, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = NetworkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with NetworkPage, status code, and headers + """ + data = values.of( + { + "IsoCountry": iso_country, + "Mcc": mcc, + "Mnc": mnc, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = NetworkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> NetworkPage: + """ + Retrieve a specific page of NetworkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return NetworkPage(self._version, response) + + async def get_page_async(self, target_url: str) -> NetworkPage: + """ + Asynchronously retrieve a specific page of NetworkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return NetworkPage(self._version, response) + + def get(self, sid: str) -> NetworkContext: + """ + Constructs a NetworkContext + + :param sid: The SID of the Network resource to fetch. + """ + return NetworkContext(self._version, sid=sid) + + def __call__(self, sid: str) -> NetworkContext: + """ + Constructs a NetworkContext + + :param sid: The SID of the Network resource to fetch. + """ + return NetworkContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/supersim/v1/network_access_profile/__init__.py b/twilio/rest/supersim/v1/network_access_profile/__init__.py new file mode 100644 index 0000000000..02c55897e5 --- /dev/null +++ b/twilio/rest/supersim/v1/network_access_profile/__init__.py @@ -0,0 +1,978 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.supersim.v1.network_access_profile.network_access_profile_network import ( + NetworkAccessProfileNetworkList, +) + + +class NetworkAccessProfileInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the Network Access Profile resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Network Access Profile belongs to. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Network Access Profile resource. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[NetworkAccessProfileContext] = None + + @property + def _proxy(self) -> "NetworkAccessProfileContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NetworkAccessProfileContext for this NetworkAccessProfileInstance + """ + if self._context is None: + self._context = NetworkAccessProfileContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "NetworkAccessProfileInstance": + """ + Fetch the NetworkAccessProfileInstance + + + :returns: The fetched NetworkAccessProfileInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NetworkAccessProfileInstance": + """ + Asynchronous coroutine to fetch the NetworkAccessProfileInstance + + + :returns: The fetched NetworkAccessProfileInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NetworkAccessProfileInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, unique_name: Union[str, object] = values.unset + ) -> "NetworkAccessProfileInstance": + """ + Update the NetworkAccessProfileInstance + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: The updated NetworkAccessProfileInstance + """ + return self._proxy.update( + unique_name=unique_name, + ) + + async def update_async( + self, unique_name: Union[str, object] = values.unset + ) -> "NetworkAccessProfileInstance": + """ + Asynchronous coroutine to update the NetworkAccessProfileInstance + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: The updated NetworkAccessProfileInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + ) + + def update_with_http_info( + self, unique_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the NetworkAccessProfileInstance with HTTP info + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + ) + + async def update_with_http_info_async( + self, unique_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the NetworkAccessProfileInstance with HTTP info + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + ) + + @property + def networks(self) -> NetworkAccessProfileNetworkList: + """ + Access the networks + """ + return self._proxy.networks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NetworkAccessProfileContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the NetworkAccessProfileContext + + :param version: Version that contains the resource + :param sid: The SID of the Network Access Profile to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/NetworkAccessProfiles/{sid}".format(**self._solution) + + self._networks: Optional[NetworkAccessProfileNetworkList] = None + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> NetworkAccessProfileInstance: + """ + Fetch the NetworkAccessProfileInstance + + + :returns: The fetched NetworkAccessProfileInstance + """ + payload, _, _ = self._fetch() + return NetworkAccessProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NetworkAccessProfileInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = NetworkAccessProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> NetworkAccessProfileInstance: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileInstance + + + :returns: The fetched NetworkAccessProfileInstance + """ + payload, _, _ = await self._fetch_async() + return NetworkAccessProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = NetworkAccessProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, unique_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, unique_name: Union[str, object] = values.unset + ) -> NetworkAccessProfileInstance: + """ + Update the NetworkAccessProfileInstance + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: The updated NetworkAccessProfileInstance + """ + payload, _, _ = self._update(unique_name=unique_name) + return NetworkAccessProfileInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def update_with_http_info( + self, unique_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the NetworkAccessProfileInstance and return response metadata + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(unique_name=unique_name) + instance = NetworkAccessProfileInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, unique_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, unique_name: Union[str, object] = values.unset + ) -> NetworkAccessProfileInstance: + """ + Asynchronous coroutine to update the NetworkAccessProfileInstance + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: The updated NetworkAccessProfileInstance + """ + payload, _, _ = await self._update_async(unique_name=unique_name) + return NetworkAccessProfileInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_async( + self, unique_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the NetworkAccessProfileInstance and return response metadata + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + unique_name=unique_name + ) + instance = NetworkAccessProfileInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def networks(self) -> NetworkAccessProfileNetworkList: + """ + Access the networks + """ + if self._networks is None: + self._networks = NetworkAccessProfileNetworkList( + self._version, + self._solution["sid"], + ) + return self._networks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NetworkAccessProfilePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> NetworkAccessProfileInstance: + """ + Build an instance of NetworkAccessProfileInstance + + :param payload: Payload response from the API + """ + + return NetworkAccessProfileInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class NetworkAccessProfileList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the NetworkAccessProfileList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/NetworkAccessProfiles" + + def _create( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> NetworkAccessProfileInstance: + """ + Create the NetworkAccessProfileInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param networks: List of Network SIDs that this Network Access Profile will allow connections to. + + :returns: The created NetworkAccessProfileInstance + """ + payload, _, _ = self._create(unique_name=unique_name, networks=networks) + return NetworkAccessProfileInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Create the NetworkAccessProfileInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, networks=networks + ) + instance = NetworkAccessProfileInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> NetworkAccessProfileInstance: + """ + Asynchronously create the NetworkAccessProfileInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param networks: List of Network SIDs that this Network Access Profile will allow connections to. + + :returns: The created NetworkAccessProfileInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, networks=networks + ) + return NetworkAccessProfileInstance(self._version, payload) + + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the NetworkAccessProfileInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, networks=networks + ) + instance = NetworkAccessProfileInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NetworkAccessProfileInstance]: + """ + Streams NetworkAccessProfileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NetworkAccessProfileInstance]: + """ + Asynchronously streams NetworkAccessProfileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams NetworkAccessProfileInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams NetworkAccessProfileInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkAccessProfileInstance]: + """ + Lists NetworkAccessProfileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkAccessProfileInstance]: + """ + Asynchronously lists NetworkAccessProfileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists NetworkAccessProfileInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists NetworkAccessProfileInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkAccessProfilePage: + """ + Retrieve a single page of NetworkAccessProfileInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkAccessProfileInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkAccessProfilePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkAccessProfilePage: + """ + Asynchronously retrieve a single page of NetworkAccessProfileInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkAccessProfileInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkAccessProfilePage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NetworkAccessProfilePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = NetworkAccessProfilePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NetworkAccessProfilePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = NetworkAccessProfilePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> NetworkAccessProfilePage: + """ + Retrieve a specific page of NetworkAccessProfileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkAccessProfileInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return NetworkAccessProfilePage(self._version, response) + + async def get_page_async(self, target_url: str) -> NetworkAccessProfilePage: + """ + Asynchronously retrieve a specific page of NetworkAccessProfileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkAccessProfileInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return NetworkAccessProfilePage(self._version, response) + + def get(self, sid: str) -> NetworkAccessProfileContext: + """ + Constructs a NetworkAccessProfileContext + + :param sid: The SID of the Network Access Profile to update. + """ + return NetworkAccessProfileContext(self._version, sid=sid) + + def __call__(self, sid: str) -> NetworkAccessProfileContext: + """ + Constructs a NetworkAccessProfileContext + + :param sid: The SID of the Network Access Profile to update. + """ + return NetworkAccessProfileContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py b/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py new file mode 100644 index 0000000000..7386d60751 --- /dev/null +++ b/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py @@ -0,0 +1,920 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class NetworkAccessProfileNetworkInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the Network resource. + :ivar network_access_profile_sid: The unique string that identifies the Network resource's Network Access Profile resource. + :ivar friendly_name: A human readable identifier of the Network this resource refers to. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resource. + :ivar identifiers: Array of objects identifying the [MCC-MNCs](https://en.wikipedia.org/wiki/Mobile_country_code) that are included in the Network resource. + :ivar url: The absolute URL of the Network resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + network_access_profile_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.network_access_profile_sid: Optional[str] = payload.get( + "network_access_profile_sid" + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iso_country: Optional[str] = payload.get("iso_country") + self.identifiers: Optional[List[Dict[str, object]]] = payload.get("identifiers") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "network_access_profile_sid": network_access_profile_sid, + "sid": sid or self.sid, + } + + self._context: Optional[NetworkAccessProfileNetworkContext] = None + + @property + def _proxy(self) -> "NetworkAccessProfileNetworkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NetworkAccessProfileNetworkContext for this NetworkAccessProfileNetworkInstance + """ + if self._context is None: + self._context = NetworkAccessProfileNetworkContext( + self._version, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the NetworkAccessProfileNetworkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the NetworkAccessProfileNetworkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the NetworkAccessProfileNetworkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the NetworkAccessProfileNetworkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "NetworkAccessProfileNetworkInstance": + """ + Fetch the NetworkAccessProfileNetworkInstance + + + :returns: The fetched NetworkAccessProfileNetworkInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NetworkAccessProfileNetworkInstance": + """ + Asynchronous coroutine to fetch the NetworkAccessProfileNetworkInstance + + + :returns: The fetched NetworkAccessProfileNetworkInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NetworkAccessProfileNetworkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileNetworkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class NetworkAccessProfileNetworkContext(InstanceContext): + + def __init__(self, version: Version, network_access_profile_sid: str, sid: str): + """ + Initialize the NetworkAccessProfileNetworkContext + + :param version: Version that contains the resource + :param network_access_profile_sid: The unique string that identifies the Network Access Profile resource. + :param sid: The SID of the Network resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "network_access_profile_sid": network_access_profile_sid, + "sid": sid, + } + self._uri = ( + "/NetworkAccessProfiles/{network_access_profile_sid}/Networks/{sid}".format( + **self._solution + ) + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the NetworkAccessProfileNetworkInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the NetworkAccessProfileNetworkInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the NetworkAccessProfileNetworkInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the NetworkAccessProfileNetworkInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> NetworkAccessProfileNetworkInstance: + """ + Fetch the NetworkAccessProfileNetworkInstance + + + :returns: The fetched NetworkAccessProfileNetworkInstance + """ + payload, _, _ = self._fetch() + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NetworkAccessProfileNetworkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> NetworkAccessProfileNetworkInstance: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileNetworkInstance + + + :returns: The fetched NetworkAccessProfileNetworkInstance + """ + payload, _, _ = await self._fetch_async() + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileNetworkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 NetworkAccessProfileNetworkPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> NetworkAccessProfileNetworkInstance: + """ + Build an instance of NetworkAccessProfileNetworkInstance + + :param payload: Payload response from the API + """ + + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class NetworkAccessProfileNetworkList(ListResource): + + def __init__(self, version: Version, network_access_profile_sid: str): + """ + Initialize the NetworkAccessProfileNetworkList + + :param version: Version that contains the resource + :param network_access_profile_sid: The unique string that identifies the Network Access Profile resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "network_access_profile_sid": network_access_profile_sid, + } + self._uri = ( + "/NetworkAccessProfiles/{network_access_profile_sid}/Networks".format( + **self._solution + ) + ) + + def _create(self, network: str) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, network: str) -> NetworkAccessProfileNetworkInstance: + """ + Create the NetworkAccessProfileNetworkInstance + + :param network: The SID of the Network resource to be added to the Network Access Profile resource. + + :returns: The created NetworkAccessProfileNetworkInstance + """ + payload, _, _ = self._create(network=network) + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + ) + + def create_with_http_info(self, network: str) -> ApiResponse: + """ + Create the NetworkAccessProfileNetworkInstance and return response metadata + + :param network: The SID of the Network resource to be added to the Network Access Profile resource. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(network=network) + instance = NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, network: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, network: str) -> NetworkAccessProfileNetworkInstance: + """ + Asynchronously create the NetworkAccessProfileNetworkInstance + + :param network: The SID of the Network resource to be added to the Network Access Profile resource. + + :returns: The created NetworkAccessProfileNetworkInstance + """ + payload, _, _ = await self._create_async(network=network) + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + ) + + async def create_with_http_info_async(self, network: str) -> ApiResponse: + """ + Asynchronously create the NetworkAccessProfileNetworkInstance and return response metadata + + :param network: The SID of the Network resource to be added to the Network Access Profile resource. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(network=network) + instance = NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NetworkAccessProfileNetworkInstance]: + """ + Streams NetworkAccessProfileNetworkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NetworkAccessProfileNetworkInstance]: + """ + Asynchronously streams NetworkAccessProfileNetworkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams NetworkAccessProfileNetworkInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams NetworkAccessProfileNetworkInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkAccessProfileNetworkInstance]: + """ + Lists NetworkAccessProfileNetworkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkAccessProfileNetworkInstance]: + """ + Asynchronously lists NetworkAccessProfileNetworkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists NetworkAccessProfileNetworkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists NetworkAccessProfileNetworkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkAccessProfileNetworkPage: + """ + Retrieve a single page of NetworkAccessProfileNetworkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkAccessProfileNetworkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkAccessProfileNetworkPage: + """ + Asynchronously retrieve a single page of NetworkAccessProfileNetworkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkAccessProfileNetworkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NetworkAccessProfileNetworkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NetworkAccessProfileNetworkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> NetworkAccessProfileNetworkPage: + """ + Retrieve a specific page of NetworkAccessProfileNetworkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkAccessProfileNetworkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) + + async def get_page_async(self, target_url: str) -> NetworkAccessProfileNetworkPage: + """ + Asynchronously retrieve a specific page of NetworkAccessProfileNetworkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkAccessProfileNetworkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) + + def get(self, sid: str) -> NetworkAccessProfileNetworkContext: + """ + Constructs a NetworkAccessProfileNetworkContext + + :param sid: The SID of the Network resource to fetch. + """ + return NetworkAccessProfileNetworkContext( + self._version, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> NetworkAccessProfileNetworkContext: + """ + Constructs a NetworkAccessProfileNetworkContext + + :param sid: The SID of the Network resource to fetch. + """ + return NetworkAccessProfileNetworkContext( + self._version, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/supersim/v1/settings_update.py b/twilio/rest/supersim/v1/settings_update.py new file mode 100644 index 0000000000..8b6f2a03a7 --- /dev/null +++ b/twilio/rest/supersim/v1/settings_update.py @@ -0,0 +1,545 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SettingsUpdateInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sim=sim, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SettingsUpdateInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sim=sim, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SettingsUpdateInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sim=sim, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SettingsUpdateInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sim=sim, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with SettingsUpdatePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SettingsUpdatePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with SettingsUpdatePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SettingsUpdatePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 5e9eb9eb3a..0000000000 --- a/twilio/rest/supersim/v1/sim.py +++ /dev/null @@ -1,425 +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'], limits['page_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): - 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..16f0046e17 --- /dev/null +++ b/twilio/rest/supersim/v1/sim/__init__.py @@ -0,0 +1,1246 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SimInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SimInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the SimInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SimInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SimInstance: + """ + Fetch the SimInstance + + + :returns: The fetched SimInstance + """ + payload, _, _ = self._fetch() + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SimInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SimInstance: + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + payload, _, _ = await self._fetch_async() + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SimInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the SimInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + instance = SimInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SimInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + instance = SimInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(iccid=iccid, registration_code=registration_code) + return SimInstance(self._version, payload) + + def create_with_http_info(self, iccid: str, registration_code: str) -> ApiResponse: + """ + Create the SimInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + iccid=iccid, registration_code=registration_code + ) + instance = SimInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, iccid: str, registration_code: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + iccid=iccid, registration_code=registration_code + ) + return SimInstance(self._version, payload) + + async def create_with_http_info_async( + self, iccid: str, registration_code: str + ) -> ApiResponse: + """ + Asynchronously create the SimInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + iccid=iccid, registration_code=registration_code + ) + instance = SimInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams SimInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, fleet=fleet, iccid=iccid, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams SimInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, fleet=fleet, iccid=iccid, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists SimInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + fleet=fleet, + iccid=iccid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists SimInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + fleet=fleet, + iccid=iccid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with SimPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SimPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with SimPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SimPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..90a0e13d3d --- /dev/null +++ b/twilio/rest/supersim/v1/sim/billing_period.py @@ -0,0 +1,490 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BillingPeriodInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BillingPeriodInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BillingPeriodInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BillingPeriodInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BillingPeriodPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BillingPeriodPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BillingPeriodPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BillingPeriodPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..9d67476a36 --- /dev/null +++ b/twilio/rest/supersim/v1/sim/sim_ip_address.py @@ -0,0 +1,469 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SimIpAddressInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SimIpAddressInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SimIpAddressInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SimIpAddressInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SimIpAddressPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SimIpAddressPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SimIpAddressPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SimIpAddressPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..3b4ce6558d --- /dev/null +++ b/twilio/rest/supersim/v1/sms_command.py @@ -0,0 +1,944 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SmsCommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SmsCommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SmsCommandInstance: + """ + Fetch the SmsCommandInstance + + + :returns: The fetched SmsCommandInstance + """ + payload, _, _ = self._fetch() + return SmsCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SmsCommandInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SmsCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SmsCommandInstance: + """ + Asynchronous coroutine to fetch the SmsCommandInstance + + + :returns: The fetched SmsCommandInstance + """ + payload, _, _ = await self._fetch_async() + return SmsCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SmsCommandInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SmsCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + sim=sim, + payload=payload, + callback_method=callback_method, + callback_url=callback_url, + ) + return SmsCommandInstance(self._version, payload) + + def create_with_http_info( + self, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the SmsCommandInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + sim=sim, + payload=payload, + callback_method=callback_method, + callback_url=callback_url, + ) + instance = SmsCommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + sim=sim, + payload=payload, + callback_method=callback_method, + callback_url=callback_url, + ) + return SmsCommandInstance(self._version, payload) + + async def create_with_http_info_async( + self, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SmsCommandInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + sim=sim, + payload=payload, + callback_method=callback_method, + callback_url=callback_url, + ) + instance = SmsCommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams SmsCommandInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sim=sim, status=status, direction=direction, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams SmsCommandInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sim=sim, status=status, direction=direction, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists SmsCommandInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists SmsCommandInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with SmsCommandPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SmsCommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with SmsCommandPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SmsCommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 962d3bda3b..05547f6d64 100644 --- a/twilio/rest/supersim/v1/usage_record.py +++ b/twilio/rest/supersim/v1/usage_record.py @@ -1,302 +1,778 @@ -# 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.api_response import ApiResponse + from twilio.base.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'], limits['page_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, - )) + page_size=limits["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): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams UsageRecordInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - Retrieve a single page of UsageRecordInstance records from the API. - Request is executed immediately + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) - :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 + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams UsageRecordInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + page_size=limits["page_size"], + ) - :returns: Page of UsageRecordInstance - :rtype: twilio.rest.supersim.v1.usage_record.UsageRecordPage + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists UsageRecordInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists UsageRecordInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: twilio.rest.supersim.v1.usage_record.UsageRecordPage - :rtype: twilio.rest.supersim.v1.usage_record.UsageRecordPage - """ - super(UsageRecordPage, self).__init__(version, response) + headers["Accept"] = "application/json" - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of UsageRecordInstance - - :param dict payload: Payload response from the API - - :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 '' - + 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 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. """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - class Granularity(object): - HOUR = "hour" - DAY = "day" - ALL = "all" + headers["Accept"] = "application/json" - class Group(object): - SIM = "sim" + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with UsageRecordPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UsageRecordPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with UsageRecordPage, status code, and headers + """ + 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, + } + ) - :returns: twilio.rest.supersim.v1.usage_record.UsageRecordInstance - :rtype: twilio.rest.supersim.v1.usage_record.UsageRecordInstance - """ - super(UsageRecordInstance, self).__init__(version) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # 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')), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {} + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UsageRecordPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def account_sid(self): - """ - :returns: The SID of the Account that incurred the usage. - :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 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): + async def get_page_async(self, target_url: str) -> UsageRecordPage: """ - :returns: Total data uploaded in bytes, aggregated by the query parameters. - :rtype: unicode - """ - 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 34ec7c49eb..a376ed7982 100644 --- a/twilio/rest/sync/v1/service/__init__.py +++ b/twilio/rest/sync/v1/service/__init__.py @@ -1,16 +1,25 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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 +27,1427 @@ 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. """ +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") - def __init__(self, version): + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[ServiceContext] = None + + @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.sync.v1.service.ServiceList - :rtype: twilio.rest.sync.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 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: True if delete succeeds, False otherwise """ - Create the ServiceInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance - :returns: The created ServiceInstance - :rtype: twilio.rest.sync.v1.service.ServiceInstance + + :returns: True if delete succeeds, False otherwise """ - 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, - }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info - return ServiceInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.ServiceInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance - :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 await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately + Fetch the ServiceInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info - return ServicePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + 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 - :returns: Page of ServiceInstance - :rtype: twilio.rest.sync.v1.service.ServicePage + :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 """ - 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 + 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, + ) - :param sid: The SID of the Service resource to fetch + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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: + """ + Access the documents """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.documents - def __call__(self, sid): + @property + def sync_lists(self) -> SyncListList: """ - Constructs a ServiceContext + Access the sync_lists + """ + return self._proxy.sync_lists - :param sid: The SID 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 + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) - def get_instance(self, payload): + self._documents: Optional[DocumentList] = None + self._sync_lists: Optional[SyncListList] = None + self._sync_maps: Optional[SyncMapList] = None + self._sync_streams: Optional[SyncStreamList] = None + + def _delete(self) -> tuple: """ - Build an instance of ServiceInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: twilio.rest.sync.v1.service.ServiceInstance - :rtype: twilio.rest.sync.v1.service.ServiceInstance + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return ServiceInstance(self._version, payload, ) + Deletes the ServiceInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the ServiceInstance and return response metadata -class ServiceContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the ServiceContext - :param Version version: Version that contains the resource - :param sid: The SID of the Service resource to fetch + headers = values.of({}) - :returns: twilio.rest.sync.v1.service.ServiceContext - :rtype: twilio.rest.sync.v1.service.ServiceContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(ServiceContext, self).__init__(version) + Asynchronous coroutine that deletes the ServiceInstance - # 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 - self._sync_streams = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) - def fetch(self): + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + 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, ) + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance and return response metadata - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - def delete(self): + :returns: ApiResponse with instance, status code, and headers """ - Deletes the ServiceInstance + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ServiceInstance: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Asynchronous coroutine to fetch the ServiceInstance - 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): + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._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 ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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({}) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + return ServiceInstance(self._version, payload) - @property - def unique_name(self): + def __repr__(self) -> str: """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] + 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): + +class ServiceList(ListResource): + + def __init__(self, version: Version): """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def _create( + self, + friendly_name: Union[str, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['friendly_name'] + Create the ServiceInstance - @property - def date_created(self): + :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: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + payload, _, _ = self._create( + friendly_name=friendly_name, + webhook_url=webhook_url, + 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 ServiceInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + webhook_url=webhook_url, + 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, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - return self._properties['date_created'] + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + webhook_url=webhook_url, + 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 ServiceInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + webhook_url=webhook_url, + 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, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def date_updated(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + 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[ServiceInstance]: """ - :returns: The absolute URL of the Service resource - :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 limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 webhook_url(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The URL we call when Sync objects are manipulated - :rtype: unicode + Streams ServiceInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['webhook_url'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def webhooks_from_rest_enabled(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: Whether the Service instance should call webhook_url when the REST API is used to update Sync objects - :rtype: bool + Asynchronously streams ServiceInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['webhooks_from_rest_enabled'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def reachability_webhooks_enabled(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: """ - :returns: Whether the service instance calls webhook_url when client endpoints connect to Sync - :rtype: 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. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to 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['reachability_webhooks_enabled'] - @property - def acl_enabled(self): + return 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]: """ - :returns: Whether token identities in the Service must be granted access to Sync objects by using the Permissions resource - :rtype: bool + 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 self._properties['acl_enabled'] - @property - def reachability_debouncing_enabled(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: Whether every endpoint_disconnected event occurs after a configurable delay - :rtype: bool + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['reachability_debouncing_enabled'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def reachability_debouncing_window(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The reachability event delay in milliseconds - :rtype: unicode + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['reachability_debouncing_window'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> ServicePage: """ - :returns: The URLs of related resources - :rtype: unicode + 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 """ - 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 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.sync.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" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) - def delete(self): + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the ServiceInstance + Retrieve a single page with response metadata - :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: ApiResponse with ServicePage, status code, and headers """ - return self._proxy.delete() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def update(self, webhook_url=values.unset, friendly_name=values.unset, - reachability_webhooks_enabled=values.unset, acl_enabled=values.unset, - reachability_debouncing_enabled=values.unset, - reachability_debouncing_window=values.unset, - webhooks_from_rest_enabled=values.unset): + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Update the ServiceInstance + Asynchronously retrieve a single page with response metadata - :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 - :returns: The updated ServiceInstance - :rtype: twilio.rest.sync.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: ApiResponse with ServicePage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ServicePage: """ - Access the documents + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.sync.v1.service.document.DocumentList - :rtype: twilio.rest.sync.v1.service.document.DocumentList + :returns: Page of ServiceInstance """ - return self._proxy.documents + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) - @property - def sync_lists(self): + async def get_page_async(self, target_url: str) -> ServicePage: """ - Access the sync_lists + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.sync.v1.service.sync_list.SyncListList - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance """ - return self._proxy.sync_lists + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) - @property - def sync_maps(self): + def get(self, sid: str) -> ServiceContext: """ - Access the sync_maps + Constructs a ServiceContext - :returns: twilio.rest.sync.v1.service.sync_map.SyncMapList - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapList + :param sid: The SID of the Service resource to update. """ - return self._proxy.sync_maps + return ServiceContext(self._version, sid=sid) - @property - def sync_streams(self): + def __call__(self, sid: str) -> ServiceContext: """ - Access the sync_streams + Constructs a ServiceContext - :returns: twilio.rest.sync.v1.service.sync_stream.SyncStreamList - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamList + :param sid: The SID of the Service resource to update. """ - return self._proxy.sync_streams + return ServiceContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/sync/v1/service/document/__init__.py b/twilio/rest/sync/v1/service/document/__init__.py index 1dd6401dda..3611fe0d18 100644 --- a/twilio/rest/sync/v1/service/document/__init__.py +++ b/twilio/rest/sync/v1/service/document/__init__.py @@ -1,506 +1,1220 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +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") - def __init__(self, version, service_sid): + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[DocumentContext] = None + + @property + def _proxy(self) -> "DocumentContext": """ - Initialize the DocumentList + 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 + :returns: DocumentContext for this DocumentInstance + """ + if self._context is None: + self._context = DocumentContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.sync.v1.service.document.DocumentList - :rtype: twilio.rest.sync.v1.service.document.DocumentList + def delete(self) -> bool: """ - super(DocumentList, self).__init__(version) + Deletes the DocumentInstance - # 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, ttl=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the DocumentInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DocumentInstance - :returns: The created DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({'UniqueName': unique_name, 'Data': serialize.object(data), 'Ttl': ttl, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DocumentInstance with HTTP info - return DocumentInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DocumentInstance with HTTP info - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "DocumentInstance": + """ + Fetch the DocumentInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "DocumentInstance": + """ + Asynchronous coroutine to fetch the DocumentInstance - :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 await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of DocumentInstance records from the API. - Request is executed immediately + Fetch the DocumentInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DocumentInstance with HTTP info - return DocumentPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of DocumentInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> "DocumentInstance": + """ + Update the DocumentInstance - :returns: Page of DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentPage + :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 """ - 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) + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> "DocumentInstance": + """ + Asynchronous coroutine to update the DocumentInstance + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). - def get(self, sid): + :returns: The updated DocumentInstance """ - Constructs a DocumentContext + return await self._proxy.update_async( + if_match=if_match, + data=data, + ttl=ttl, + ) + + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the DocumentInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return DocumentContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + if_match=if_match, + data=data, + ttl=ttl, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Constructs a DocumentContext + Asynchronous coroutine to update the DocumentInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return DocumentContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + if_match=if_match, + data=data, + ttl=ttl, + ) - def __repr__(self): + @property + def document_permissions(self) -> DocumentPermissionList: + """ + Access the document_permissions + """ + return self._proxy.document_permissions + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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) -> tuple: """ - Build an instance of DocumentInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.sync.v1.service.document.DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentInstance + def delete(self) -> bool: """ - return DocumentInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the DocumentInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the DocumentInstance and return response metadata -class DocumentContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the DocumentContext + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes 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: True if delete succeeds, False otherwise """ - super(DocumentContext, self).__init__(version) + success, _, _ = await self._delete_async() + return success - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Documents/{sid}'.format(**self._solution) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DocumentInstance and return response metadata - # Dependents - self._document_permissions = None - def fetch(self): + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DocumentInstance: """ Fetch the DocumentInstance + :returns: The fetched DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DocumentInstance and return response metadata + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DocumentInstance: + """ + Asynchronous coroutine to fetch the DocumentInstance + + + :returns: The fetched DocumentInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the DocumentInstance + Asynchronous coroutine to fetch the DocumentInstance and return response metadata - :param unicode if_match: The If-Match HTTP request header - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: """ - headers = values.of({'If-Match': if_match, }) + Internal helper for update operation - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + Returns: + tuple: (payload, status_code, 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 - def update(self, data=values.unset, ttl=values.unset, if_match=values.unset): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: """ Update the DocumentInstance - :param 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._update(if_match=if_match, data=data, ttl=ttl) + return DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the DocumentInstance and return response metadata + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + if_match=if_match, data=data, ttl=ttl + ) + instance = DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: + """ + Asynchronous coroutine to update the DocumentInstance + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: The updated DocumentInstance + """ + payload, _, _ = await self._update_async(if_match=if_match, data=data, ttl=ttl) 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"], + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DocumentInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + if_match=if_match, data=data, ttl=ttl + ) + instance = DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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'), +class DocumentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DocumentInstance: + """ + Build an instance of DocumentInstance + + :param payload: Payload response from the API + """ + + return DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DocumentList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the DocumentList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Document resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/Documents".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - 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.sync.v1.service.document.DocumentContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: """ - if self._context is None: - self._context = DocumentContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the DocumentInstance - @property - def sid(self): + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: The created DocumentInstance """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = self._create(unique_name=unique_name, data=data, ttl=ttl) + return DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['sid'] + Create the DocumentInstance and return response metadata - @property - def unique_name(self): + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: ApiResponse with instance, status code, and headers """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + payload, status_code, headers = self._create( + unique_name=unique_name, data=data, ttl=ttl + ) + instance = DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: """ - return self._properties['unique_name'] + Internal async helper for create operation - @property - def account_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the Account that created the resource - :rtype: unicode + + data = values.of( + { + "UniqueName": unique_name, + "Data": serialize.object(data), + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: """ - return self._properties['account_sid'] + Asynchronously create the DocumentInstance - @property - def service_sid(self): + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: The created DocumentInstance """ - :returns: The SID of the Sync Service that the resource is associated with - :rtype: unicode + payload, _, _ = await self._create_async( + unique_name=unique_name, data=data, ttl=ttl + ) + return DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['service_sid'] + Asynchronously create the DocumentInstance and return response metadata - @property - def url(self): + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The absolute URL of the Document resource - :rtype: unicode + payload, status_code, headers = await self._create_async( + unique_name=unique_name, data=data, ttl=ttl + ) + instance = DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DocumentInstance]: """ - return self._properties['url'] + Streams DocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - @property - def 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 resources related to the Sync Document - :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[DocumentInstance]: """ - return self._properties['links'] + Asynchronously streams DocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - @property - def revision(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 current revision of the Sync Document, represented by a string identifier - :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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['revision'] + Streams DocumentInstance and returns headers from first page - @property - def data(self): + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: An arbitrary, schema-less object that the Sync Document stores - :rtype: dict + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['data'] + Asynchronously streams DocumentInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The ISO 8601 date and time in GMT when the Sync Document expires - :rtype: datetime + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DocumentInstance]: """ - return self._properties['date_expires'] + Lists DocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def date_created(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The 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[DocumentInstance]: """ - return self._properties['date_created'] + Asynchronously lists DocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def date_updated(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Lists DocumentInstance and returns headers from first page - @property - def created_by(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: ApiResponse with list of instances, status code, and headers """ - :returns: The identity of the Sync Document's creator - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['created_by'] + Asynchronously lists DocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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: ApiResponse with list of instances, status code, and headers """ - Fetch the DocumentInstance + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: The fetched DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentInstance + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DocumentPage: """ - return self._proxy.fetch() + Retrieve a single page of DocumentInstance records from the API. + Request is executed immediately - def delete(self, if_match=values.unset): + :param page_token: PageToken provided by the API + :param page_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 """ - Deletes the DocumentInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :param unicode if_match: The If-Match HTTP request header + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: True if delete succeeds, False otherwise - :rtype: bool + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DocumentPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DocumentPage: """ - return self._proxy.delete(if_match=if_match, ) + Asynchronously retrieve a single page of DocumentInstance records from the API. + Request is executed immediately - def update(self, data=values.unset, ttl=values.unset, if_match=values.unset): + :param page_token: PageToken provided by the API + :param page_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 """ - Update the DocumentInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :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 + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: The updated DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentInstance + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DocumentPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.update(data=data, ttl=ttl, if_match=if_match, ) + Retrieve a single page with response metadata - @property - def document_permissions(self): + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DocumentPage, status code, and headers """ - Access the document_permissions + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionList - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionList + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DocumentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.document_permissions + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DocumentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DocumentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> DocumentPage: + """ + Retrieve a specific page of DocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DocumentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DocumentPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> DocumentPage: + """ + Asynchronously retrieve a specific page of DocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DocumentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DocumentPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> DocumentContext: + """ + Constructs a DocumentContext + + :param sid: The SID of the Document resource to update. Can be the Document resource's `sid` or its `unique_name`. + """ + return DocumentContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> DocumentContext: + """ + Constructs a DocumentContext + + :param sid: The SID of the Document resource to update. Can be the Document resource's `sid` or its `unique_name`. + """ + return DocumentContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 59dacce957..16f87b9cd1 100644 --- a/twilio/rest/sync/v1/service/document/document_permission.py +++ b/twilio/rest/sync/v1/service/document/document_permission.py @@ -1,439 +1,1022 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class DocumentPermissionList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class DocumentPermissionInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Document Permission resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar document_sid: The SID of the Sync Document to which the Document Permission applies. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the Service to an FPA token. + :ivar read: Whether the identity can read the Sync Document. + :ivar write: Whether the identity can update the Sync Document. + :ivar manage: Whether the identity can delete the Sync Document. + :ivar url: The absolute URL of the Sync Document Permission resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + document_sid: str, + identity: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.document_sid: Optional[str] = payload.get("document_sid") + self.identity: Optional[str] = payload.get("identity") + self.read: Optional[bool] = payload.get("read") + self.write: Optional[bool] = payload.get("write") + self.manage: Optional[bool] = payload.get("manage") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "document_sid": document_sid, + "identity": identity or self.identity, + } + + self._context: Optional[DocumentPermissionContext] = None - def __init__(self, version, service_sid, document_sid): + @property + def _proxy(self) -> "DocumentPermissionContext": """ - Initialize the DocumentPermissionList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The SID of the Sync Service that the resource is associated with - :param document_sid: The Sync Document SID + :returns: DocumentPermissionContext for this DocumentPermissionInstance + """ + if self._context is None: + self._context = DocumentPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + return self._context - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionList - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionList + def delete(self) -> bool: """ - super(DocumentPermissionList, self).__init__(version) + Deletes the DocumentPermissionInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'document_sid': document_sid, } - self._uri = '/Services/{service_sid}/Documents/{document_sid}/Permissions'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - Streams DocumentPermissionInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + 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 DocumentPermissionInstance - :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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DocumentPermissionInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists DocumentPermissionInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DocumentPermissionInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_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, }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "DocumentPermissionInstance": + """ + Asynchronous coroutine to fetch the DocumentPermissionInstance - return DocumentPermissionPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched DocumentPermissionInstance """ - Retrieve a specific page of DocumentPermissionInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DocumentPermissionInstance with HTTP info - :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DocumentPermissionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, read: bool, write: bool, manage: bool + ) -> "DocumentPermissionInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Update the DocumentPermissionInstance + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: The updated DocumentPermissionInstance + """ + return self._proxy.update( + read=read, + write=write, + manage=manage, ) - return DocumentPermissionPage(self._version, response, self._solution) + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> "DocumentPermissionInstance": + """ + Asynchronous coroutine to update the DocumentPermissionInstance - def get(self, identity): + :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 """ - Constructs a DocumentPermissionContext + return await self._proxy.update_async( + read=read, + write=write, + manage=manage, + ) - :param identity: The application-defined string that uniquely identifies the User's Document Permission resource to fetch + def update_with_http_info( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Update the DocumentPermissionInstance with HTTP info - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionContext - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionContext + :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: ApiResponse with instance, status code, and headers """ - return DocumentPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - document_sid=self._solution['document_sid'], - identity=identity, + return self._proxy.update_with_http_info( + read=read, + write=write, + manage=manage, ) - def __call__(self, identity): + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: """ - Constructs a DocumentPermissionContext + Asynchronous coroutine to update the DocumentPermissionInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return DocumentPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - document_sid=self._solution['document_sid'], - identity=identity, + return await self._proxy.update_with_http_info_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) -> tuple: """ - Build an instance of DocumentPermissionInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return DocumentPermissionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - document_sid=self._solution['document_sid'], + Deletes the DocumentPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DocumentPermissionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + 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 '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DocumentPermissionInstance and return response metadata -class DocumentPermissionContext(InstanceContext): - """ 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, identity): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the DocumentPermissionContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionContext - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionContext + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> DocumentPermissionInstance: """ 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, ) + payload, _, _ = self._fetch() + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DocumentPermissionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DocumentPermissionInstance: + """ + Asynchronous coroutine to fetch the DocumentPermissionInstance + + :returns: The fetched DocumentPermissionInstance + """ + payload, _, _ = await self._fetch_async() return DocumentPermissionInstance( self._version, payload, - service_sid=self._solution['service_sid'], - document_sid=self._solution['document_sid'], - identity=self._solution['identity'], + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], ) - def delete(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the DocumentPermissionInstance + Asynchronous coroutine to fetch the DocumentPermissionInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, read: bool, write: bool, manage: bool) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for update operation - def update(self, read, write, manage): + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, read: bool, write: bool, manage: bool + ) -> DocumentPermissionInstance: """ 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._update(read=read, write=write, manage=manage) + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + + def update_with_http_info( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Update the DocumentPermissionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + read=read, write=write, manage=manage + ) + instance = DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, read: bool, write: bool, manage: bool) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> DocumentPermissionInstance: + """ + Asynchronous coroutine to update the DocumentPermissionInstance - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :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 + """ + payload, _, _ = await self._update_async(read=read, write=write, manage=manage) 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): + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DocumentPermissionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + read=read, write=write, manage=manage + ) + instance = DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide 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) - # 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'), - } + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + - # Context - self._context = None +class DocumentPermissionList(ListResource): + + def __init__(self, version: Version, service_sid: str, document_sid: str): + """ + Initialize the DocumentPermissionList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Document Permission resources to read. + :param document_sid: The SID of the Sync Document with the Document Permission resources to read. Can be the Document resource's `sid` or its `unique_name`. + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'document_sid': document_sid, - 'identity': identity or self._properties['identity'], + "service_sid": service_sid, + "document_sid": document_sid, } + self._uri = ( + "/Services/{service_sid}/Documents/{document_sid}/Permissions".format( + **self._solution + ) + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DocumentPermissionInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: DocumentPermissionContext for this DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionContext + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = DocumentPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - document_sid=self._solution['document_sid'], - identity=self._solution['identity'], - ) - return self._context + 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[DocumentPermissionInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Asynchronously streams DocumentPermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Sync Service that the resource is associated with - :rtype: unicode + Streams DocumentPermissionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['service_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def document_sid(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The Sync Document SID - :rtype: unicode + Asynchronously streams DocumentPermissionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['document_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def identity(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DocumentPermissionInstance]: """ - :returns: The identity of the user to whom the Sync Document Permission applies - :rtype: unicode + Lists DocumentPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['identity'] - @property - def read(self): + return 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]: """ - :returns: Read access - :rtype: bool + Asynchronously lists DocumentPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['read'] - @property - def write(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: Write access - :rtype: bool + Lists DocumentPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['write'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def manage(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: Manage access - :rtype: bool + Asynchronously lists DocumentPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['manage'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> DocumentPermissionPage: """ - :returns: The absolute URL of the Sync Document Permission resource - :rtype: unicode + Retrieve a single page of DocumentPermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DocumentPermissionInstance """ - return self._properties['url'] + 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 DocumentPermissionPage(self._version, response, solution=self._solution) + + async def 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: """ - Fetch the DocumentPermissionInstance + Asynchronously retrieve a single page of DocumentPermissionInstance records from the API. + Request is executed immediately - :returns: The fetched DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance + :param page_token: PageToken provided by the API + :param page_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 """ - 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 DocumentPermissionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the DocumentPermissionInstance + Retrieve a single page with response metadata - :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: ApiResponse with DocumentPermissionPage, status code, and headers """ - 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, read, write, manage): + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DocumentPermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Update the DocumentPermissionInstance + Asynchronously retrieve a single page with response metadata - :param bool read: Read access - :param bool write: Write access - :param bool manage: Manage access - :returns: The updated DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DocumentPermissionPage, status code, and headers """ - return self._proxy.update(read, write, manage, ) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DocumentPermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> DocumentPermissionPage: + """ + Retrieve a specific page of DocumentPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DocumentPermissionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DocumentPermissionPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> DocumentPermissionPage: + """ + Asynchronously retrieve a specific page of DocumentPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DocumentPermissionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DocumentPermissionPage(self._version, response, solution=self._solution) + + def get(self, identity: str) -> DocumentPermissionContext: + """ + Constructs a DocumentPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Document Permission resource to update. + """ + return DocumentPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=identity, + ) + + def __call__(self, identity: str) -> DocumentPermissionContext: + """ + Constructs a DocumentPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Document Permission resource to update. + """ + return DocumentPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=identity, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 de8e609e5a..e757173ab9 100644 --- a/twilio/rest/sync/v1/service/sync_list/__init__.py +++ b/twilio/rest/sync/v1/service/sync_list/__init__.py @@ -1,516 +1,1210 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +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") - def __init__(self, version, service_sid): + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[SyncListContext] = None + + @property + def _proxy(self) -> "SyncListContext": """ - Initialize the SyncListList + 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 + :returns: SyncListContext for this SyncListInstance + """ + if self._context is None: + self._context = SyncListContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.sync.v1.service.sync_list.SyncListList - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListList + def delete(self) -> bool: """ - super(SyncListList, self).__init__(version) + Deletes the SyncListInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Lists'.format(**self._solution) - def create(self, unique_name=values.unset, ttl=values.unset, - collection_ttl=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the SyncListInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncListInstance - :returns: The created SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({'UniqueName': unique_name, 'Ttl': ttl, 'CollectionTtl': collection_ttl, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncListInstance with HTTP info - return SyncListInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_list.SyncListInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "SyncListInstance": + """ + Fetch the SyncListInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "SyncListInstance": + """ + Asynchronous coroutine to fetch the SyncListInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_list.SyncListInstance] + + :returns: The fetched SyncListInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of SyncListInstance records from the API. - Request is executed immediately + Fetch the SyncListInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncListInstance with HTTP info - return SyncListPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of SyncListInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncListInstance": + """ + Update the SyncListInstance - :returns: Page of SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListPage + :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 """ - 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) + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncListInstance": + """ + Asynchronous coroutine to update the SyncListInstance + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. - def get(self, sid): + :returns: The updated SyncListInstance """ - Constructs a SyncListContext + return await self._proxy.update_async( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + def update_with_http_info( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the SyncListInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return SyncListContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + ttl=ttl, + collection_ttl=collection_ttl, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Constructs a SyncListContext + Asynchronous coroutine to update the SyncListInstance with HTTP info + + :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. - :param sid: The SID of the Sync List resource to fetch + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + @property + def sync_list_items(self) -> SyncListItemList: + """ + Access the sync_list_items + """ + return self._proxy.sync_list_items - :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: """ - return SyncListContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Access the sync_list_permissions + """ + 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) + + self._sync_list_items: Optional[SyncListItemList] = None + self._sync_list_permissions: Optional[SyncListPermissionList] = None - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of SyncListInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.sync.v1.service.sync_list.SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance + def delete(self) -> bool: """ - return SyncListInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the SyncListInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the SyncListInstance and return response metadata -class SyncListContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the SyncListContext + Internal async helper for delete operation - :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: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.sync.v1.service.sync_list.SyncListContext - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListContext + async def delete_async(self) -> bool: """ - super(SyncListContext, self).__init__(version) + Asynchronous coroutine that deletes the SyncListInstance - # 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 + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> SyncListInstance: """ 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, ) + payload, _, _ = self._fetch() + return SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncListInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SyncListInstance: + """ + Asynchronous coroutine to fetch the SyncListInstance + + + :returns: The fetched SyncListInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the SyncListInstance + Asynchronous coroutine to fetch the SyncListInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation - def update(self, ttl=values.unset, collection_ttl=values.unset): + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: """ 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._update(ttl=ttl, collection_ttl=collection_ttl) + return SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the SyncListInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ - 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: + """ + Asynchronous coroutine to update the SyncListInstance + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The updated SyncListInstance + """ + payload, _, _ = await self._update_async(ttl=ttl, collection_ttl=collection_ttl) 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"], ) + async def update_with_http_info_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncListInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @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'), +class SyncListPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncListInstance: + """ + Build an instance of SyncListInstance + + :param payload: Payload response from the API + """ + + return SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SyncListList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the SyncListList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync List resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/Lists".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - 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.sync.v1.service.sync_list.SyncListContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: """ - if self._context is None: - self._context = SyncListContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the SyncListInstance - @property - def 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: 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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = self._create( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + return SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['sid'] + Create the SyncListInstance and return response metadata - @property - def unique_name(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: 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: ApiResponse with instance, status code, and headers """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + payload, status_code, headers = self._create( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: """ - return self._properties['unique_name'] + Internal async helper for create operation - @property - def account_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the Account that created the resource - :rtype: unicode + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._properties['account_sid'] + Asynchronously create the SyncListInstance - @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: 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 """ - :returns: The SID of the Sync Service that the resource is associated with - :rtype: unicode + payload, _, _ = await self._create_async( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + return SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['service_sid'] + Asynchronously create the SyncListInstance and return response metadata - @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: 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: ApiResponse with instance, status code, and headers """ - :returns: The absolute URL of the Sync List resource - :rtype: unicode + payload, status_code, headers = await self._create_async( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncListInstance]: """ - return self._properties['url'] + 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. - @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 Sync List'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[SyncListInstance]: """ - return self._properties['links'] + 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. - @property - def revision(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 current revision of the Sync List, represented as a string - :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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['revision'] + Streams SyncListInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The ISO 8601 date and time in GMT when the Sync List expires - :rtype: datetime + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_expires'] + Asynchronously streams SyncListInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :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_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListInstance]: """ - return self._properties['date_created'] + Lists SyncListInstance 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[SyncListInstance]: """ - return self._properties['date_updated'] + 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. - @property - def created_by(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 identity of the Sync List's creator - :rtype: unicode + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['created_by'] + Lists SyncListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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: ApiResponse with list of instances, status code, and headers """ - Fetch the SyncListInstance + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: The fetched SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.fetch() + Asynchronously lists SyncListInstance and returns headers from first page + - 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: ApiResponse with list of instances, status code, and headers """ - Deletes the SyncListInstance + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + 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: """ - return self._proxy.delete() + 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 - def update(self, ttl=values.unset, collection_ttl=values.unset): + :returns: Page of SyncListInstance """ - Update the SyncListInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :param unicode ttl: An alias for collection_ttl - :param unicode collection_ttl: How long, in seconds, before the Sync List expires and is deleted + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: The updated SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncListPage(self._version, response, solution=self._solution) + + async def 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: """ - return self._proxy.update(ttl=ttl, collection_ttl=collection_ttl, ) + Asynchronously retrieve a single page of SyncListInstance records from the API. + Request is executed immediately - @property - def sync_list_items(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 SyncListInstance """ - Access the sync_list_items + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemList - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemList + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncListPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.sync_list_items + Retrieve a single page with response metadata - @property - def sync_list_permissions(self): + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncListPage, status code, and headers """ - Access the sync_list_permissions + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionList - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionList + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SyncListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.sync_list_permissions + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncListPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SyncListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> SyncListPage: + """ + Retrieve a specific page of SyncListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncListPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> SyncListPage: + """ + Asynchronously retrieve a specific page of SyncListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncListPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> SyncListContext: + """ + Constructs a SyncListContext + + :param sid: The SID of the Sync List resource to update. Can be the Sync List resource's `sid` or its `unique_name`. + """ + return SyncListContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> SyncListContext: + """ + Constructs a SyncListContext + + :param sid: The SID of the Sync List resource to update. Can be the Sync List resource's `sid` or its `unique_name`. + """ + return SyncListContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 34d1770ff8..40dfcbadf9 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,1460 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + + class QueryFromBoundType(object): + INCLUSIVE = "inclusive" + EXCLUSIVE = "exclusive" + + class QueryResultOrder(object): + ASC = "asc" + DESC = "desc" + + """ + :ivar index: The automatically generated index of the List Item. The `index` values of the List Items in a Sync List can have gaps in their sequence. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the List Item resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar list_sid: The SID of the Sync List that contains the List Item. + :ivar url: The absolute URL of the List Item resource. + :ivar revision: The current revision of the item, represented as a string. + :ivar data: An arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :ivar date_expires: The date and time in GMT when the List Item expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the List Item does not expire, this value is `null`. The List Item resource might not be deleted immediately after it expires. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The identity of the List Item's creator. If the item is created from the client SDK, the value matches the Access Token's `identity` field. If the item was created from the REST API, the value is `system`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + list_sid: str, + index: Optional[int] = None, + ): + super().__init__(version) + + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.list_sid: Optional[str] = payload.get("list_sid") + self.url: Optional[str] = payload.get("url") + self.revision: Optional[str] = payload.get("revision") + self.data: Optional[Dict[str, object]] = payload.get("data") + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") - def __init__(self, version, service_sid, list_sid): + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + "index": index or self.index, + } + + self._context: Optional[SyncListItemContext] = None + + @property + def _proxy(self) -> "SyncListItemContext": """ - Initialize the SyncListItemList + 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 that contains the List Item + :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: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemList - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemList + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - super(SyncListItemList, self).__init__(version) + Deletes the SyncListItemInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'list_sid': list_sid, } - self._uri = '/Services/{service_sid}/Lists/{list_sid}/Items'.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). - def create(self, data, ttl=values.unset, item_ttl=values.unset, - collection_ttl=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the SyncListItemInstance + return self._proxy.delete( + if_match=if_match, + ) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the SyncListItemInstance - :param 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 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: The created SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + if_match=if_match, + ) + + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: """ - data = values.of({ - 'Data': serialize.object(data), - 'Ttl': ttl, - 'ItemTtl': item_ttl, - 'CollectionTtl': collection_ttl, - }) + Deletes the SyncListItemInstance with HTTP info - 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: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + if_match=if_match, ) - def stream(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: """ - 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 with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async( + if_match=if_match, + ) - page = self.page(order=order, from_=from_, bounds=bounds, page_size=limits['page_size'], ) + def fetch(self) -> "SyncListItemInstance": + """ + Fetch the SyncListItemInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() + + async def fetch_async(self) -> "SyncListItemInstance": + """ + 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance] + :returns: The fetched SyncListItemInstance """ - return list(self.stream(order=order, from_=from_, bounds=bounds, limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, order=values.unset, from_=values.unset, bounds=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of SyncListItemInstance records from the API. - Request is executed immediately + Fetch the SyncListItemInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Order': order, - 'From': from_, - 'Bounds': bounds, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncListItemInstance with HTTP info - return SyncListItemPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of SyncListItemInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + 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 - :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 self._proxy.update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, ) - return SyncListItemPage(self._version, response, self._solution) + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncListItemInstance": + """ + Asynchronous coroutine to update the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. - def get(self, index): + :returns: The updated SyncListItemInstance """ - Constructs a SyncListItemContext + return await self._proxy.update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) - :param index: The index of the Sync List Item resource to fetch + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the SyncListItemInstance with HTTP info + + :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: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemContext - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemContext + :returns: ApiResponse with instance, status code, and headers """ - return SyncListItemContext( - self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - index=index, + return self._proxy.update_with_http_info( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, ) - def __call__(self, index): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Constructs a SyncListItemContext + Asynchronous coroutine to update the SyncListItemInstance with HTTP info - :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). + :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: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemContext - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemContext + :returns: ApiResponse with instance, status code, and headers """ - return SyncListItemContext( - self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - index=index, + return await self._proxy.update_with_http_info_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, ) - 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 SyncListItemPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncListItemContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, list_sid: str, index: int): """ - Initialize the SyncListItemPage - - :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 + Initialize the SyncListItemContext - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemPage - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemPage + :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(SyncListItemPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def _delete(self, if_match: Union[str, object] = values.unset) -> tuple: """ - Build an instance of SyncListItemInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "If-Match": if_match, + } + ) - :param dict payload: Payload response from the API + headers = values.of({}) - :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 self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], + Deletes the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete(if_match=if_match) + return success + + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the SyncListItemInstance and return response metadata + + :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: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self, if_match: Union[str, object] = values.unset) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 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 '' + success, _, _ = await self._delete_async(if_match=if_match) + return success + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListItemInstance and return response metadata -class SyncListItemContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :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). - def __init__(self, version, service_sid, list_sid, index): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the SyncListItemContext + success, status_code, headers = await self._delete_async(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, 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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :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: + tuple: (payload, status_code, headers) """ - 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) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> 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, ) + payload, _, _ = self._fetch() + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncListItemInstance and return response metadata + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SyncListItemInstance: + """ + Asynchronous coroutine to fetch the SyncListItemInstance + + + :returns: The fetched SyncListItemInstance + """ + payload, _, _ = await self._fetch_async() 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 fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the SyncListItemInstance + Asynchronous coroutine to fetch the SyncListItemInstance and return response metadata - :param unicode if_match: The If-Match HTTP request header - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: ApiResponse with instance, status code, and headers """ - headers = values.of({'If-Match': if_match, }) + payload, status_code, headers = await self._fetch_async() + instance = SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - def update(self, data=values.unset, ttl=values.unset, item_ttl=values.unset, - collection_ttl=values.unset, 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, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListItemInstance: """ Update the SyncListItemInstance - :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 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 - :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, }) + payload, _, _ = self._update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the SyncListItemInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + instance = SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + :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 + """ + payload, _, _ = await self._update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) 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"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncListItemInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + instance = SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 +class SyncListItemList(ListResource): + + def __init__(self, version: Version, service_sid: str, list_sid: str): + """ + Initialize the SyncListItemList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the List Item resources to read. + :param list_sid: The SID of the Sync List with the List Items to read. Can be the Sync List resource's `sid` or its `unique_name`. + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'list_sid': list_sid, - 'index': index or self._properties['index'], + "service_sid": service_sid, + "list_sid": list_sid, } + self._uri = "/Services/{service_sid}/Lists/{list_sid}/Items".format( + **self._solution + ) - @property - def _proxy(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, + ) -> tuple: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Internal helper for create operation - :returns: SyncListItemContext for this SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemContext + Returns: + tuple: (payload, status_code, headers) """ - 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): + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 automatically generated index of the List Item - :rtype: unicode + Create the SyncListItemInstance + + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListItemInstance """ - return self._properties['index'] + payload, _, _ = self._create( + data=data, ttl=ttl, item_ttl=item_ttl, collection_ttl=collection_ttl + ) + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) - @property - def account_sid(self): + def create_with_http_info( + self, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Create the SyncListItemInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['account_sid'] + payload, status_code, headers = self._create( + data=data, ttl=ttl, item_ttl=item_ttl, collection_ttl=collection_ttl + ) + instance = SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def service_sid(self): + 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, + ) -> tuple: """ - :returns: The SID of the Sync Service that the resource is associated with - :rtype: unicode + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['service_sid'] - @property - def list_sid(self): + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListItemInstance: """ - :returns: The SID of the Sync List that contains the List Item - :rtype: unicode + Asynchronously create the SyncListItemInstance + + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListItemInstance """ - return self._properties['list_sid'] + payload, _, _ = await self._create_async( + data=data, ttl=ttl, item_ttl=item_ttl, collection_ttl=collection_ttl + ) + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) - @property - def url(self): + async def create_with_http_info_async( + self, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The absolute URL of the List Item resource - :rtype: unicode + Asynchronously create the SyncListItemInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + data=data, ttl=ttl, item_ttl=item_ttl, collection_ttl=collection_ttl + ) + instance = SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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['url'] + 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 revision(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 current revision of the item, represented as a string - :rtype: unicode + 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['revision'] + 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 data(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: An arbitrary, schema-less object that the List Item stores - :rtype: dict + 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 stream_with_http_info( + 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, + ) -> tuple: """ - return self._properties['data'] + Streams SyncListItemInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :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_response = self.page_with_http_info( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - return self._properties['date_expires'] + Asynchronously streams SyncListItemInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :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_response = await self.page_with_http_info_async( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists SyncListItemInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists SyncListItemInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with SyncListItemPage, status code, and headers + """ + data = values.of( + { + "Order": order, + "From": from_, + "Bounds": bounds, + "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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SyncListItemPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with SyncListItemPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SyncListItemPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 86668a984f..620954de44 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,1022 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class SyncListPermissionList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncListPermissionInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync List Permission resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar list_sid: The SID of the Sync List to which the Permission applies. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the Service to an FPA token. + :ivar read: Whether the identity can read the Sync List and its Items. + :ivar write: Whether the identity can create, update, and delete Items in the Sync List. + :ivar manage: Whether the identity can delete the Sync List. + :ivar url: The absolute URL of the Sync List Permission resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + list_sid: str, + identity: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.list_sid: Optional[str] = payload.get("list_sid") + self.identity: Optional[str] = payload.get("identity") + self.read: Optional[bool] = payload.get("read") + self.write: Optional[bool] = payload.get("write") + self.manage: Optional[bool] = payload.get("manage") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + "identity": identity or self.identity, + } + + self._context: Optional[SyncListPermissionContext] = None - def __init__(self, version, service_sid, list_sid): + @property + def _proxy(self) -> "SyncListPermissionContext": """ - Initialize the SyncListPermissionList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: 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. + 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 SyncListPermissionInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance] + + :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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncListPermissionInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists SyncListPermissionInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListPermissionInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "SyncListPermissionInstance": """ - Retrieve a single page of SyncListPermissionInstance records from the API. - Request is executed immediately + 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 self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "SyncListPermissionInstance": + """ + Asynchronous coroutine to fetch the SyncListPermissionInstance - return SyncListPermissionPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched SyncListPermissionInstance """ - Retrieve a specific page of SyncListPermissionInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncListPermissionInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionPage + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncListPermissionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, read: bool, write: bool, manage: bool + ) -> "SyncListPermissionInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Update the SyncListPermissionInstance + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: The updated SyncListPermissionInstance + """ + return self._proxy.update( + read=read, + write=write, + manage=manage, ) - return SyncListPermissionPage(self._version, response, self._solution) + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> "SyncListPermissionInstance": + """ + Asynchronous coroutine to update the SyncListPermissionInstance - def get(self, identity): + :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 """ - Constructs a SyncListPermissionContext + return await self._proxy.update_async( + read=read, + write=write, + manage=manage, + ) - :param identity: The application-defined string that uniquely identifies the User's Sync List Permission resource to fetch + def update_with_http_info( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Update the SyncListPermissionInstance with HTTP info - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionContext - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionContext + :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: ApiResponse with instance, status code, and headers """ - return SyncListPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - identity=identity, + return self._proxy.update_with_http_info( + read=read, + write=write, + manage=manage, ) - def __call__(self, identity): + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: """ - Constructs a SyncListPermissionContext + Asynchronous coroutine to update the SyncListPermissionInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return SyncListPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - identity=identity, + return await self._proxy.update_with_http_info_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 SyncListPermissionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncListPermissionContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__( + self, version: Version, service_sid: str, list_sid: str, identity: str + ): """ - Initialize the SyncListPermissionPage - - :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 + Initialize the SyncListPermissionContext - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionPage - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionPage + :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(SyncListPermissionPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of SyncListPermissionInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return SyncListPermissionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], + Deletes the SyncListPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncListPermissionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the SyncListPermissionInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListPermissionInstance and return response metadata -class SyncListPermissionContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, service_sid, list_sid, identity): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the SyncListPermissionContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :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: + tuple: (payload, status_code, headers) """ - 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) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncListPermissionInstance: """ Fetch the SyncListPermissionInstance + :returns: The fetched SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncListPermissionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SyncListPermissionInstance: + """ + Asynchronous coroutine to fetch the SyncListPermissionInstance + + + :returns: The fetched SyncListPermissionInstance + """ + payload, _, _ = await self._fetch_async() return SyncListPermissionInstance( self._version, payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - identity=self._solution['identity'], + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], ) - def delete(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the SyncListPermissionInstance + Asynchronous coroutine to fetch the SyncListPermissionInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def update(self, read, write, manage): + def _update(self, read: bool, write: bool, manage: bool) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, read: bool, write: bool, manage: bool + ) -> SyncListPermissionInstance: """ Update the SyncListPermissionInstance - :param bool read: Read access - :param bool write: Write access - :param bool manage: Manage access + :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 - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance """ - data = values.of({'Read': read, 'Write': write, 'Manage': manage, }) + payload, _, _ = self._update(read=read, write=write, manage=manage) + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + + def update_with_http_info( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Update the SyncListPermissionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + read=read, write=write, manage=manage + ) + instance = SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, read: bool, write: bool, manage: bool) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> SyncListPermissionInstance: + """ + Asynchronous coroutine to update the SyncListPermissionInstance - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :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, _, _ = await self._update_async(read=read, write=write, manage=manage) return SyncListPermissionInstance( self._version, payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - identity=self._solution['identity'], + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], ) - def __repr__(self): + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncListPermissionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + read=read, write=write, manage=manage + ) + instance = SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SyncListPermissionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncListPermissionPage(Page): - def __init__(self, version, payload, service_sid, list_sid, identity=None): + def get_instance(self, payload: Dict[str, Any]) -> SyncListPermissionInstance: """ - Initialize the SyncListPermissionInstance + Build an instance of SyncListPermissionInstance - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance + :param payload: Payload response from the API """ - super(SyncListPermissionInstance, self).__init__(version) - # Marshaled Properties - self._properties = { - 'account_sid': payload.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'), - } + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SyncListPermissionList(ListResource): - # Context - self._context = None + def __init__(self, version: Version, service_sid: str, list_sid: str): + """ + Initialize the SyncListPermissionList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync List Permission resources to read. + :param list_sid: The SID of the Sync List with the Sync List Permission resources to read. Can be the Sync List resource's `sid` or its `unique_name`. + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'list_sid': list_sid, - '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 + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = SyncListPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - identity=self._solution['identity'], - ) - return self._context + 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[SyncListPermissionInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Asynchronously streams SyncListPermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Sync Service that the resource is associated with - :rtype: unicode + Streams SyncListPermissionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['service_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def list_sid(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Sync List to which the Permission applies - :rtype: unicode + Asynchronously streams SyncListPermissionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['list_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def identity(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListPermissionInstance]: """ - :returns: The identity of the user to whom the Sync List Permission applies - :rtype: unicode + Lists SyncListPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['identity'] - @property - def read(self): + return 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]: """ - :returns: Read access - :rtype: bool + Asynchronously lists SyncListPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['read'] - @property - def write(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: Write access - :rtype: bool + Lists SyncListPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['write'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def manage(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: Manage access - :rtype: bool + Asynchronously lists SyncListPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['manage'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> SyncListPermissionPage: """ - :returns: The absolute URL of the Sync List Permission resource - :rtype: unicode + Retrieve a single page of SyncListPermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncListPermissionInstance """ - return self._properties['url'] + 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 SyncListPermissionPage(self._version, response, solution=self._solution) + + async def 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: """ - Fetch the SyncListPermissionInstance + Asynchronously retrieve a single page of SyncListPermissionInstance records from the API. + Request is executed immediately - :returns: The fetched SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance + :param page_token: PageToken provided by the API + :param page_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 """ - 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 SyncListPermissionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the SyncListPermissionInstance + Retrieve a single page with response metadata - :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: ApiResponse with SyncListPermissionPage, status code, and headers """ - 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, read, write, manage): + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SyncListPermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Update the SyncListPermissionInstance + Asynchronously retrieve a single page with response metadata - :param bool read: Read access - :param bool write: Write access - :param bool manage: Manage access - :returns: The updated SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncListPermissionPage, status code, and headers """ - return self._proxy.update(read, write, manage, ) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SyncListPermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> SyncListPermissionPage: + """ + Retrieve a specific page of SyncListPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListPermissionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncListPermissionPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> SyncListPermissionPage: + """ + Asynchronously retrieve a specific page of SyncListPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListPermissionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncListPermissionPage(self._version, response, solution=self._solution) + + def get(self, identity: str) -> SyncListPermissionContext: + """ + Constructs a SyncListPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Sync List Permission resource to update. + """ + return SyncListPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=identity, + ) + + def __call__(self, identity: str) -> SyncListPermissionContext: + """ + Constructs a SyncListPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Sync List Permission resource to update. + """ + return SyncListPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=identity, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 b986e2bc4c..1c5049b798 100644 --- a/twilio/rest/sync/v1/service/sync_map/__init__.py +++ b/twilio/rest/sync/v1/service/sync_map/__init__.py @@ -1,516 +1,1210 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +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") - def __init__(self, version, service_sid): + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[SyncMapContext] = None + + @property + def _proxy(self) -> "SyncMapContext": """ - Initialize the SyncMapList + 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 + :returns: SyncMapContext for this SyncMapInstance + """ + if self._context is None: + self._context = SyncMapContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.sync.v1.service.sync_map.SyncMapList - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapList + def delete(self) -> bool: """ - super(SyncMapList, self).__init__(version) + Deletes the SyncMapInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Maps'.format(**self._solution) - def create(self, unique_name=values.unset, ttl=values.unset, - collection_ttl=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the SyncMapInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncMapInstance - :returns: The created SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({'UniqueName': unique_name, 'Ttl': ttl, 'CollectionTtl': collection_ttl, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncMapInstance with HTTP info - return SyncMapInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_map.SyncMapInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "SyncMapInstance": + """ + Fetch the SyncMapInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "SyncMapInstance": + """ + Asynchronous coroutine to fetch the SyncMapInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_map.SyncMapInstance] + + :returns: The fetched SyncMapInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of SyncMapInstance records from the API. - Request is executed immediately + Fetch the SyncMapInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncMapInstance with HTTP info - return SyncMapPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of SyncMapInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncMapInstance": + """ + Update the SyncMapInstance - :returns: Page of SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapPage + :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 """ - 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) + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncMapInstance": + """ + Asynchronous coroutine to update the SyncMapInstance + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. - def get(self, sid): + :returns: The updated SyncMapInstance """ - Constructs a SyncMapContext + return await self._proxy.update_async( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + def update_with_http_info( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the SyncMapInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return SyncMapContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + ttl=ttl, + collection_ttl=collection_ttl, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Constructs a SyncMapContext + Asynchronous coroutine to update the SyncMapInstance with HTTP info + + :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. - :param sid: The SID of the Sync Map resource to fetch + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + @property + def sync_map_items(self) -> SyncMapItemList: + """ + Access the sync_map_items + """ + return self._proxy.sync_map_items - :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: """ - return SyncMapContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Access the sync_map_permissions + """ + 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) + + self._sync_map_items: Optional[SyncMapItemList] = None + self._sync_map_permissions: Optional[SyncMapPermissionList] = None - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of SyncMapInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.sync.v1.service.sync_map.SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapInstance + def delete(self) -> bool: """ - return SyncMapInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the SyncMapInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the SyncMapInstance and return response metadata -class SyncMapContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the SyncMapContext + Internal async helper for delete operation - :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: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.sync.v1.service.sync_map.SyncMapContext - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapContext + async def delete_async(self) -> bool: """ - super(SyncMapContext, self).__init__(version) + Asynchronous coroutine that deletes the SyncMapInstance - # 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 + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> SyncMapInstance: """ 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, ) + payload, _, _ = self._fetch() + return SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncMapInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SyncMapInstance: + """ + Asynchronous coroutine to fetch the SyncMapInstance + + + :returns: The fetched SyncMapInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the SyncMapInstance + Asynchronous coroutine to fetch the SyncMapInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation - def update(self, ttl=values.unset, collection_ttl=values.unset): + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: """ 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._update(ttl=ttl, collection_ttl=collection_ttl) + return SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the SyncMapInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ - 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: + """ + Asynchronous coroutine to update the SyncMapInstance + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The updated SyncMapInstance + """ + payload, _, _ = await self._update_async(ttl=ttl, collection_ttl=collection_ttl) 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"], ) + async def update_with_http_info_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncMapInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @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'), +class SyncMapPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncMapInstance: + """ + Build an instance of SyncMapInstance + + :param payload: Payload response from the API + """ + + return SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SyncMapList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the SyncMapList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync Map resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/Maps".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - 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.sync.v1.service.sync_map.SyncMapContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: """ - if self._context is None: - self._context = SyncMapContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the SyncMapInstance - @property - def sid(self): + :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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, _, _ = self._create( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + return SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['sid'] + Create the SyncMapInstance and return response metadata - @property - def unique_name(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + payload, status_code, headers = self._create( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: """ - return self._properties['unique_name'] + Internal async helper for create operation - @property - def account_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the Account that created the resource - :rtype: unicode + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._properties['account_sid'] + Asynchronously create the SyncMapInstance - @property - def service_sid(self): + :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 """ - :returns: The SID of the Sync Service that the resource is associated with - :rtype: unicode + payload, _, _ = await self._create_async( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + return SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['service_sid'] + Asynchronously create the SyncMapInstance and return response metadata - @property - def url(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The absolute URL of the Sync Map resource - :rtype: unicode + payload, status_code, headers = await self._create_async( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncMapInstance]: """ - return self._properties['url'] + 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. - @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 Sync Map'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[SyncMapInstance]: """ - return self._properties['links'] + 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. - @property - def revision(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 current revision of the Sync Map, represented as a string - :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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['revision'] + Streams SyncMapInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The ISO 8601 date and time in GMT when the Sync Map expires - :rtype: datetime + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_expires'] + Asynchronously streams SyncMapInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :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_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapInstance]: """ - return self._properties['date_created'] + Lists SyncMapInstance 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[SyncMapInstance]: """ - return self._properties['date_updated'] + 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. - @property - def created_by(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 identity of the Sync Map's creator - :rtype: unicode + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['created_by'] + Lists SyncMapInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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: ApiResponse with list of instances, status code, and headers """ - Fetch the SyncMapInstance + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: The fetched SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapInstance + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.fetch() + Asynchronously lists SyncMapInstance and returns headers from first page + - 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: ApiResponse with list of instances, status code, and headers """ - Deletes the SyncMapInstance + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + 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: """ - return self._proxy.delete() + 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 - def update(self, ttl=values.unset, collection_ttl=values.unset): + :returns: Page of SyncMapInstance """ - Update the SyncMapInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :param unicode ttl: An alias for collection_ttl - :param unicode collection_ttl: How long, in seconds, before the Sync Map expires and is deleted + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: The updated SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapInstance + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncMapPage(self._version, response, solution=self._solution) + + async def 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: """ - return self._proxy.update(ttl=ttl, collection_ttl=collection_ttl, ) + Asynchronously retrieve a single page of SyncMapInstance records from the API. + Request is executed immediately - @property - def sync_map_items(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 SyncMapInstance """ - Access the sync_map_items + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemList - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemList + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncMapPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.sync_map_items + Retrieve a single page with response metadata - @property - def sync_map_permissions(self): + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncMapPage, status code, and headers """ - Access the sync_map_permissions + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionList - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionList + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SyncMapPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._proxy.sync_map_permissions + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncMapPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SyncMapPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> SyncMapPage: + """ + Retrieve a specific page of SyncMapInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncMapPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> SyncMapPage: + """ + Asynchronously retrieve a specific page of SyncMapInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncMapPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> SyncMapContext: + """ + Constructs a SyncMapContext + + :param sid: The SID of the Sync Map resource to update. Can be the Sync Map's `sid` or its `unique_name`. + """ + return SyncMapContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> SyncMapContext: + """ + Constructs a SyncMapContext + + :param sid: The SID of the Sync Map resource to update. Can be the Sync Map's `sid` or its `unique_name`. + """ + return SyncMapContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 cffb0bef19..e63720c278 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,1488 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + + class QueryFromBoundType(object): + INCLUSIVE = "inclusive" + EXCLUSIVE = "exclusive" - def __init__(self, version, service_sid, map_sid): + class QueryResultOrder(object): + ASC = "asc" + DESC = "desc" + + """ + :ivar key: The unique, user-defined key for the Map Item. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Map Item resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar map_sid: The SID of the Sync Map that contains the Map Item. + :ivar url: The absolute URL of the Map Item resource. + :ivar revision: The current revision of the Map Item, represented as a string. + :ivar data: An arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :ivar date_expires: The date and time in GMT when the Map Item expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Map Item does not expire, this value is `null`. The Map Item might not be deleted immediately after it expires. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The identity of the Map Item's creator. If the Map Item is created from the client SDK, the value matches the Access Token's `identity` field. If the Map Item was created from the REST API, the value is `system`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + map_sid: str, + key: Optional[str] = None, + ): + super().__init__(version) + + self.key: Optional[str] = payload.get("key") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.map_sid: Optional[str] = payload.get("map_sid") + self.url: Optional[str] = payload.get("url") + self.revision: Optional[str] = payload.get("revision") + self.data: Optional[Dict[str, object]] = payload.get("data") + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + "key": key or self.key, + } + + self._context: Optional[SyncMapItemContext] = None + + @property + def _proxy(self) -> "SyncMapItemContext": """ - Initialize the SyncMapItemList + 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: The SID of the Sync Map that contains the Map Item + :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: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemList - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemList + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - super(SyncMapItemList, self).__init__(version) + Deletes the SyncMapItemInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'map_sid': map_sid, } - self._uri = '/Services/{service_sid}/Maps/{map_sid}/Items'.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). - def create(self, key, data, ttl=values.unset, item_ttl=values.unset, - collection_ttl=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the SyncMapItemInstance + return self._proxy.delete( + if_match=if_match, + ) - :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 + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the SyncMapItemInstance - :returns: The created SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'Key': key, - 'Data': serialize.object(data), - 'Ttl': ttl, - 'ItemTtl': item_ttl, - 'CollectionTtl': collection_ttl, - }) + return await self._proxy.delete_async( + if_match=if_match, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the SyncMapItemInstance with HTTP info - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], + :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: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + if_match=if_match, ) - def stream(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: """ - 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 with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async( + if_match=if_match, + ) + + def fetch(self) -> "SyncMapItemInstance": + """ + Fetch the SyncMapItemInstance - page = self.page(order=order, from_=from_, bounds=bounds, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched SyncMapItemInstance + """ + return self._proxy.fetch() - def list(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): + async def fetch_async(self) -> "SyncMapItemInstance": """ - Lists SyncMapItemInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine to fetch the SyncMapItemInstance - :param SyncMapItemInstance.QueryResultOrder order: 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 await self._proxy.fetch_async() - def page(self, order=values.unset, from_=values.unset, bounds=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of SyncMapItemInstance records from the API. - Request is executed immediately + Fetch the SyncMapItemInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - data = values.of({ - 'Order': order, - 'From': from_, - 'Bounds': bounds, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncMapItemInstance with HTTP info - return SyncMapItemPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of SyncMapItemInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + 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 - :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 self._proxy.update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, ) - return SyncMapItemPage(self._version, response, self._solution) + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncMapItemInstance": + """ + Asynchronous coroutine to update the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. - def get(self, key): + :returns: The updated SyncMapItemInstance """ - Constructs a SyncMapItemContext + return await self._proxy.update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) - :param key: The key value of the Sync Map Item resource to fetch + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the SyncMapItemInstance with HTTP info + + :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: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemContext - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemContext + :returns: ApiResponse with instance, status code, and headers """ - return SyncMapItemContext( - self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - key=key, + return self._proxy.update_with_http_info( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, ) - def __call__(self, key): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Constructs a SyncMapItemContext + Asynchronous coroutine to update the SyncMapItemInstance with HTTP info - :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). + :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: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemContext - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemContext + :returns: ApiResponse with instance, status code, and headers """ - return SyncMapItemContext( - self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - key=key, + return await self._proxy.update_with_http_info_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, ) - 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 SyncMapItemPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncMapItemContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, map_sid: str, key: str): """ - Initialize the SyncMapItemPage - - :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 + Initialize the SyncMapItemContext - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemPage - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemPage + :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(SyncMapItemPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def _delete(self, if_match: Union[str, object] = values.unset) -> tuple: """ - Build an instance of SyncMapItemInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "If-Match": if_match, + } + ) - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], + Deletes the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete(if_match=if_match) + return success + + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the SyncMapItemInstance and return response metadata + + :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: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self, if_match: Union[str, object] = values.unset) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 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 '' + success, _, _ = await self._delete_async(if_match=if_match) + return success + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapItemInstance and return response metadata -class SyncMapItemContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :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). - def __init__(self, version, service_sid, map_sid, key): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the SyncMapItemContext + success, status_code, headers = await self._delete_async(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, 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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :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: + tuple: (payload, status_code, headers) """ - 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) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> 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, ) + payload, _, _ = self._fetch() + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncMapItemInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SyncMapItemInstance: + """ + Asynchronous coroutine to fetch the SyncMapItemInstance + + + :returns: The fetched SyncMapItemInstance + """ + payload, _, _ = await self._fetch_async() 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 fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the SyncMapItemInstance + Asynchronous coroutine to fetch the SyncMapItemInstance and return response metadata - :param unicode if_match: The If-Match HTTP request header - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: ApiResponse with instance, status code, and headers """ - headers = values.of({'If-Match': if_match, }) + payload, status_code, headers = await self._fetch_async() + instance = SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + headers["Accept"] = "application/json" - def update(self, data=values.unset, ttl=values.unset, item_ttl=values.unset, - collection_ttl=values.unset, if_match=values.unset): + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapItemInstance: """ Update the SyncMapItemInstance - :param 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 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 - :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, }) + payload, _, _ = self._update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the SyncMapItemInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + instance = SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + :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 + """ + payload, _, _ = await self._update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) 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): + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncMapItemInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + instance = SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide 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 + """ - def __init__(self, version, payload, service_sid, map_sid, key=None): + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + + 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 + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + } + self._uri = "/Services/{service_sid}/Maps/{map_sid}/Items".format( + **self._solution + ) + + def _create( + self, + key: str, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._properties['key'] + Create the SyncMapItemInstance - @property - def account_sid(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: The SID of the Account that created the resource - :rtype: unicode + payload, _, _ = self._create( + key=key, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['account_sid'] + Create the SyncMapItemInstance and return response metadata - @property - def service_sid(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: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Sync Service that the resource is associated with - :rtype: unicode + payload, status_code, headers = self._create( + key=key, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + instance = SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['service_sid'] + Asynchronously create the SyncMapItemInstance - @property - def map_sid(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: The SID of the Sync Map that contains the Map Item - :rtype: unicode + payload, _, _ = await self._create_async( + key=key, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + + async def create_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['map_sid'] + Asynchronously create the SyncMapItemInstance and return response metadata - @property - def url(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: ApiResponse with instance, status code, and headers """ - :returns: The absolute URL of the Map Item resource - :rtype: unicode + payload, status_code, headers = await self._create_async( + key=key, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + instance = SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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['url'] + 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 revision(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 current revision of the Map Item, represented as a string - :rtype: unicode + 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['revision'] + 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 data(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: An arbitrary, schema-less object that the Map Item stores - :rtype: dict + 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 stream_with_http_info( + 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, + ) -> tuple: """ - return self._properties['data'] + Streams SyncMapItemInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :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_response = self.page_with_http_info( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - return self._properties['date_expires'] + Asynchronously streams SyncMapItemInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :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_response = await self.page_with_http_info_async( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists SyncMapItemInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists SyncMapItemInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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"}) - def fetch(self): + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncMapItemPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with SyncMapItemPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SyncMapItemPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with SyncMapItemPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SyncMapItemPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 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, + ) - :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 + def __call__(self, key: str) -> SyncMapItemContext: + """ + Constructs a SyncMapItemContext - :returns: The updated SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance + :param key: The `key` value of the Sync Map Item resource to update. """ - return self._proxy.update( - data=data, - ttl=ttl, - item_ttl=item_ttl, - collection_ttl=collection_ttl, - if_match=if_match, + 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 9e15d91920..eb210e017b 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,1020 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class SyncMapPermissionList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncMapPermissionInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync Map Permission resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar map_sid: The SID of the Sync Map to which the Permission applies. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the Service to an FPA token. + :ivar read: Whether the identity can read the Sync Map and its Items. + :ivar write: Whether the identity can create, update, and delete Items in the Sync Map. + :ivar manage: Whether the identity can delete the Sync Map. + :ivar url: The absolute URL of the Sync Map Permission resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + map_sid: str, + identity: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.map_sid: Optional[str] = payload.get("map_sid") + self.identity: Optional[str] = payload.get("identity") + self.read: Optional[bool] = payload.get("read") + self.write: Optional[bool] = payload.get("write") + self.manage: Optional[bool] = payload.get("manage") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + "identity": identity or self.identity, + } + + self._context: Optional[SyncMapPermissionContext] = None - def __init__(self, version, service_sid, map_sid): + @property + def _proxy(self) -> "SyncMapPermissionContext": """ - Initialize the SyncMapPermissionList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: 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. + 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 SyncMapPermissionInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance] + + :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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncMapPermissionInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists SyncMapPermissionInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapPermissionInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "SyncMapPermissionInstance": """ - Retrieve a single page of SyncMapPermissionInstance records from the API. - Request is executed immediately + 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 self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "SyncMapPermissionInstance": + """ + Asynchronous coroutine to fetch the SyncMapPermissionInstance - return SyncMapPermissionPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched SyncMapPermissionInstance """ - Retrieve a specific page of SyncMapPermissionInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncMapPermissionInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionPage + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncMapPermissionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, read: bool, write: bool, manage: bool + ) -> "SyncMapPermissionInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Update the SyncMapPermissionInstance + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: The updated SyncMapPermissionInstance + """ + return self._proxy.update( + read=read, + write=write, + manage=manage, ) - return SyncMapPermissionPage(self._version, response, self._solution) + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> "SyncMapPermissionInstance": + """ + Asynchronous coroutine to update the SyncMapPermissionInstance - def get(self, identity): + :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 """ - Constructs a SyncMapPermissionContext + return await self._proxy.update_async( + read=read, + write=write, + manage=manage, + ) - :param identity: The application-defined string that uniquely identifies the User's Sync Map Permission resource to fetch + def update_with_http_info( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Update the SyncMapPermissionInstance with HTTP info - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionContext - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionContext + :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: ApiResponse with instance, status code, and headers """ - return SyncMapPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - identity=identity, + return self._proxy.update_with_http_info( + read=read, + write=write, + manage=manage, ) - def __call__(self, identity): + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: """ - Constructs a SyncMapPermissionContext + Asynchronous coroutine to update the SyncMapPermissionInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return SyncMapPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - identity=identity, + return await self._proxy.update_with_http_info_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 SyncMapPermissionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncMapPermissionContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, map_sid: str, identity: str): """ - Initialize the SyncMapPermissionPage - - :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 + Initialize the SyncMapPermissionContext - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionPage - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionPage + :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(SyncMapPermissionPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of SyncMapPermissionInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return SyncMapPermissionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], + Deletes the SyncMapPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncMapPermissionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) - def __repr__(self): + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the SyncMapPermissionInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapPermissionInstance and return response metadata -class SyncMapPermissionContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, service_sid, map_sid, identity): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the SyncMapPermissionContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :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: + tuple: (payload, status_code, headers) """ - 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) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncMapPermissionInstance: """ Fetch the SyncMapPermissionInstance + :returns: The fetched SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncMapPermissionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SyncMapPermissionInstance: + """ + Asynchronous coroutine to fetch the SyncMapPermissionInstance + + + :returns: The fetched SyncMapPermissionInstance + """ + payload, _, _ = await self._fetch_async() return SyncMapPermissionInstance( self._version, payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - identity=self._solution['identity'], + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], ) - def delete(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the SyncMapPermissionInstance + Asynchronous coroutine to fetch the SyncMapPermissionInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def update(self, read, write, manage): + def _update(self, read: bool, write: bool, manage: bool) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, read: bool, write: bool, manage: bool + ) -> SyncMapPermissionInstance: """ Update the SyncMapPermissionInstance - :param bool read: Read access - :param bool write: Write access - :param bool manage: Manage access + :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 - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance """ - data = values.of({'Read': read, 'Write': write, 'Manage': manage, }) + payload, _, _ = self._update(read=read, write=write, manage=manage) + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + + def update_with_http_info( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Update the SyncMapPermissionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + read=read, write=write, manage=manage + ) + instance = SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, read: bool, write: bool, manage: bool) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> SyncMapPermissionInstance: + """ + Asynchronous coroutine to update the SyncMapPermissionInstance - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :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, _, _ = await self._update_async(read=read, write=write, manage=manage) return SyncMapPermissionInstance( self._version, payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - identity=self._solution['identity'], + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], ) - def __repr__(self): + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncMapPermissionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + read=read, write=write, manage=manage + ) + instance = SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SyncMapPermissionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncMapPermissionPage(Page): - def __init__(self, version, payload, service_sid, map_sid, identity=None): + def get_instance(self, payload: Dict[str, Any]) -> SyncMapPermissionInstance: """ - Initialize the SyncMapPermissionInstance + Build an instance of SyncMapPermissionInstance - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance + :param payload: Payload response from the API """ - super(SyncMapPermissionInstance, self).__init__(version) - # Marshaled Properties - self._properties = { - 'account_sid': payload.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'), - } + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SyncMapPermissionList(ListResource): - # Context - self._context = None + def __init__(self, version: Version, service_sid: str, map_sid: str): + """ + Initialize the SyncMapPermissionList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync Map Permission resources to read. Can be the Service's `sid` value or `default`. + :param map_sid: The SID of the Sync Map with the Permission resources to read. Can be the Sync Map resource's `sid` or its `unique_name`. + + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'map_sid': map_sid, - '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 + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = SyncMapPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - identity=self._solution['identity'], - ) - return self._context + 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[SyncMapPermissionInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Asynchronously streams SyncMapPermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SID of the Sync Service that the resource is associated with - :rtype: unicode + Streams SyncMapPermissionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['service_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def map_sid(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: Sync Map SID - :rtype: unicode + Asynchronously streams SyncMapPermissionInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['map_sid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def identity(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapPermissionInstance]: """ - :returns: The identity of the user to whom the Sync Document Permission applies - :rtype: unicode + Lists SyncMapPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['identity'] - @property - def read(self): + return 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]: """ - :returns: Read access - :rtype: bool + Asynchronously lists SyncMapPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['read'] - @property - def write(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: Write access - :rtype: bool + Lists SyncMapPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['write'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def manage(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: Manage access - :rtype: bool + Asynchronously lists SyncMapPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['manage'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> SyncMapPermissionPage: """ - :returns: The absolute URL of the Sync Map Permission resource - :rtype: unicode + Retrieve a single page of SyncMapPermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncMapPermissionInstance """ - return self._properties['url'] + 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 SyncMapPermissionPage(self._version, response, solution=self._solution) + + async def 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: """ - Fetch the SyncMapPermissionInstance + Asynchronously retrieve a single page of SyncMapPermissionInstance records from the API. + Request is executed immediately - :returns: The fetched SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance + :param page_token: PageToken provided by the API + :param page_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 """ - 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 SyncMapPermissionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the SyncMapPermissionInstance + Retrieve a single page with response metadata - :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: ApiResponse with SyncMapPermissionPage, status code, and headers """ - 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, read, write, manage): + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SyncMapPermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Update the SyncMapPermissionInstance + Asynchronously retrieve a single page with response metadata - :param bool read: Read access - :param bool write: Write access - :param bool manage: Manage access - :returns: The updated SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncMapPermissionPage, status code, and headers """ - return self._proxy.update(read, write, manage, ) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SyncMapPermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> SyncMapPermissionPage: + """ + Retrieve a specific page of SyncMapPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapPermissionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncMapPermissionPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> SyncMapPermissionPage: + """ + Asynchronously retrieve a specific page of SyncMapPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapPermissionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncMapPermissionPage(self._version, response, solution=self._solution) + + def get(self, identity: str) -> SyncMapPermissionContext: + """ + Constructs a SyncMapPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Sync Map Permission resource to update. + """ + return SyncMapPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=identity, + ) + + def __call__(self, identity: str) -> SyncMapPermissionContext: + """ + Constructs a SyncMapPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Sync Map Permission resource to update. + """ + return SyncMapPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=identity, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 6b2ee53384..f233231d44 100644 --- a/twilio/rest/sync/v1/service/sync_stream/__init__.py +++ b/twilio/rest/sync/v1/service/sync_stream/__init__.py @@ -1,475 +1,1120 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +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") - def __init__(self, version, service_sid): + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[SyncStreamContext] = None + + @property + def _proxy(self) -> "SyncStreamContext": """ - Initialize the SyncStreamList + 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 + :returns: SyncStreamContext for this SyncStreamInstance + """ + if self._context is None: + self._context = SyncStreamContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.sync.v1.service.sync_stream.SyncStreamList - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamList + def delete(self) -> bool: """ - super(SyncStreamList, self).__init__(version) + Deletes the SyncStreamInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Streams'.format(**self._solution) - def create(self, unique_name=values.unset, ttl=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the SyncStreamInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncStreamInstance - :returns: The created SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({'UniqueName': unique_name, 'Ttl': ttl, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncStreamInstance with HTTP info - return SyncStreamInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncStreamInstance with HTTP info - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "SyncStreamInstance": + """ + Fetch the SyncStreamInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "SyncStreamInstance": + """ + Asynchronous coroutine to fetch the SyncStreamInstance - :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 await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of SyncStreamInstance records from the API. - Request is executed immediately + Fetch the SyncStreamInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncStreamInstance with HTTP info - return SyncStreamPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of SyncStreamInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update(self, ttl: Union[int, object] = values.unset) -> "SyncStreamInstance": + """ + Update the SyncStreamInstance - :returns: Page of SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamPage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + ttl=ttl, ) - return SyncStreamPage(self._version, response, self._solution) + async def update_async( + self, ttl: Union[int, object] = values.unset + ) -> "SyncStreamInstance": + """ + Asynchronous coroutine to update the SyncStreamInstance + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). - def get(self, sid): + :returns: The updated SyncStreamInstance """ - Constructs a SyncStreamContext + return await self._proxy.update_async( + ttl=ttl, + ) + + def update_with_http_info( + self, ttl: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Update the SyncStreamInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return SyncStreamContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + ttl=ttl, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, ttl: Union[int, object] = values.unset + ) -> ApiResponse: """ - Constructs a SyncStreamContext + Asynchronous coroutine to update the SyncStreamInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return SyncStreamContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + ttl=ttl, + ) - def __repr__(self): + @property + def stream_messages(self) -> StreamMessageList: + """ + Access the stream_messages + """ + return self._proxy.stream_messages + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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) -> tuple: """ - Build an instance of SyncStreamInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance + def delete(self) -> bool: """ - return SyncStreamInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the SyncStreamInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the SyncStreamInstance and return response metadata -class SyncStreamContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the SyncStreamContext + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes 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: True if delete succeeds, False otherwise """ - super(SyncStreamContext, self).__init__(version) + success, _, _ = await self._delete_async() + return success - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Streams/{sid}'.format(**self._solution) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncStreamInstance and return response metadata - # Dependents - self._stream_messages = None - def fetch(self): + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncStreamInstance: """ 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, ) + payload, _, _ = self._fetch() + return SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncStreamInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SyncStreamInstance: + """ + Asynchronous coroutine to fetch the SyncStreamInstance + + + :returns: The fetched SyncStreamInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the SyncStreamInstance + Asynchronous coroutine to fetch the SyncStreamInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, ttl: Union[int, object] = values.unset) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for update operation - def update(self, ttl=values.unset): + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, ttl: Union[int, object] = values.unset) -> SyncStreamInstance: """ 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._update(ttl=ttl) + return SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def update_with_http_info( + self, ttl: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Update the SyncStreamInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(ttl=ttl) + instance = SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, ttl: Union[int, object] = values.unset) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({}) + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, ttl: Union[int, object] = values.unset + ) -> SyncStreamInstance: + """ + Asynchronous coroutine to update the SyncStreamInstance + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The updated SyncStreamInstance + """ + payload, _, _ = await self._update_async(ttl=ttl) 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"], + ) + + async def update_with_http_info_async( + self, ttl: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncStreamInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(ttl=ttl) + instance = SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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'), +class SyncStreamPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncStreamInstance: + """ + Build an instance of SyncStreamInstance + + :param payload: Payload response from the API + """ + + return SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SyncStreamList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the SyncStreamList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Stream resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/Streams".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: SyncStreamContext for this SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> SyncStreamInstance: """ - if self._context is None: - self._context = SyncStreamContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the SyncStreamInstance - @property - def 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 unique string that identifies the resource - :rtype: unicode + payload, _, _ = self._create(unique_name=unique_name, ttl=ttl) + return SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['sid'] + Create the SyncStreamInstance and return response metadata - @property - def unique_name(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: ApiResponse with instance, status code, and headers """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + payload, status_code, headers = self._create(unique_name=unique_name, ttl=ttl) + instance = SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: """ - return self._properties['unique_name'] + Internal async helper for create operation - @property - def account_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the Account that created the 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> SyncStreamInstance: """ - return self._properties['account_sid'] + Asynchronously 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 + payload, _, _ = await self._create_async(unique_name=unique_name, ttl=ttl) + return SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['service_sid'] + Asynchronously create the SyncStreamInstance and return response metadata - @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: ApiResponse with instance, status code, and headers """ - :returns: The absolute URL of the Message Stream resource - :rtype: unicode + payload, status_code, headers = await self._create_async( + unique_name=unique_name, ttl=ttl + ) + instance = SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_expires'] + Streams SyncStreamInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :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_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['date_created'] + Asynchronously streams SyncStreamInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :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_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncStreamInstance]: """ - return self._properties['date_updated'] + 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 created_by(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 Identity of the Stream's creator - :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[SyncStreamInstance]: """ - return self._properties['created_by'] + 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. - 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 SyncStreamInstance - :returns: The fetched SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.fetch() + Lists SyncStreamInstance and returns headers from first page - 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: ApiResponse with list of instances, status code, and headers """ - Deletes the SyncStreamInstance + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.delete() + Asynchronously lists SyncStreamInstance and returns headers from first page - def update(self, ttl=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: ApiResponse with list of instances, status code, and headers """ - Update the SyncStreamInstance + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncStreamPage: + """ + Retrieve a single page of SyncStreamInstance records from the API. + Request is executed immediately - :param unicode ttl: How long, in seconds, before the Stream expires and is deleted + :param page_token: PageToken provided by the API + :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 SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance + :returns: Page of SyncStreamInstance """ - return self._proxy.update(ttl=ttl, ) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def stream_messages(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 SyncStreamPage(self._version, response, solution=self._solution) + + async def 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: """ - Access the stream_messages + Asynchronously retrieve a single page of SyncStreamInstance records from the API. + Request is executed immediately - :returns: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageList - :rtype: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageList + :param page_token: PageToken provided by the API + :param page_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 """ - return self._proxy.stream_messages + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncStreamPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SyncStreamPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncStreamPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SyncStreamPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> SyncStreamPage: + """ + Retrieve a specific page of SyncStreamInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncStreamInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncStreamPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> SyncStreamPage: + """ + Asynchronously retrieve a specific page of SyncStreamInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncStreamInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncStreamPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> SyncStreamContext: + """ + Constructs a SyncStreamContext + + :param sid: The SID of the Stream resource to update. + """ + return SyncStreamContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> SyncStreamContext: + """ + Constructs a SyncStreamContext + + :param sid: The SID of the Stream resource to update. + """ + return SyncStreamContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..f7646d1936 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,197 @@ -# 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.api_response import ApiResponse + 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) -> tuple: """ - Create the StreamMessageInstance - - :param dict data: A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body + Internal helper for create operation - :returns: The created StreamMessageInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageInstance + Returns: + tuple: (payload, status_code, headers) """ - 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 - - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" -class StreamMessagePage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __init__(self, version, response, solution): + def create(self, data: object) -> StreamMessageInstance: """ - Initialize the StreamMessagePage + Create the StreamMessageInstance - :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 + :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: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessagePage - :rtype: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessagePage + :returns: The created StreamMessageInstance """ - super(StreamMessagePage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = self._create(data=data) + return StreamMessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + stream_sid=self._solution["stream_sid"], + ) - def get_instance(self, payload): + def create_with_http_info(self, data: object) -> ApiResponse: """ - Build an instance of StreamMessageInstance + Create the StreamMessageInstance and return response metadata - :param dict payload: Payload response from the API + :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: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageInstance + :returns: ApiResponse with instance, status code, and headers """ - return StreamMessageInstance( + payload, status_code, headers = self._create(data=data) + instance = 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"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _create_async(self, data: object) -> tuple: """ - Provide a friendly representation + Internal async helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + data = values.of( + { + "Data": serialize.object(data), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class StreamMessageInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, payload, service_sid, stream_sid): - """ - Initialize the StreamMessageInstance + headers["Accept"] = "application/json" - :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) + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - # Marshaled Properties - self._properties = {'sid': payload.get('sid'), 'data': payload.get('data'), } + async def create_async(self, data: object) -> StreamMessageInstance: + """ + Asynchronously create the StreamMessageInstance - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'stream_sid': stream_sid, } + :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. - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: The created StreamMessageInstance """ - return self._properties['sid'] + payload, _, _ = await self._create_async(data=data) + return StreamMessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + stream_sid=self._solution["stream_sid"], + ) - @property - def data(self): + async def create_with_http_info_async(self, data: object) -> ApiResponse: """ - :returns: Stream Message body - :rtype: dict + Asynchronously create the StreamMessageInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['data'] + payload, status_code, headers = await self._create_async(data=data) + instance = StreamMessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + stream_sid=self._solution["stream_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 bf420029f8..5e857c3d0a 100644 --- a/twilio/rest/taskrouter/v1/workspace/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/__init__.py @@ -1,16 +1,25 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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,636 +28,669 @@ from twilio.rest.taskrouter.v1.workspace.task_queue import TaskQueueList from twilio.rest.taskrouter.v1.workspace.worker import WorkerList from twilio.rest.taskrouter.v1.workspace.workflow import WorkflowList -from twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics import WorkspaceCumulativeStatisticsList -from twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics import WorkspaceRealTimeStatisticsList -from twilio.rest.taskrouter.v1.workspace.workspace_statistics import WorkspaceStatisticsList - - -class WorkspaceList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the WorkspaceList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.taskrouter.v1.workspace.WorkspaceList - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceList - """ - super(WorkspaceList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Workspaces'.format(**self._solution) - - def stream(self, friendly_name=values.unset, limit=None, page_size=None): - """ - 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 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) +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, +) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.WorkspaceInstance] - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(friendly_name=friendly_name, page_size=limits['page_size'], ) +class WorkspaceInstance(InstanceResource): - return self._version.stream(page, limits['limit'], limits['page_limit']) + class QueueOrder(object): + FIFO = "FIFO" + LIFO = "LIFO" - def list(self, friendly_name=values.unset, limit=None, page_size=None): - """ - Lists WorkspaceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + """ + :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") - :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) + self._solution = { + "sid": sid or self.sid, + } - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.WorkspaceInstance] - """ - return list(self.stream(friendly_name=friendly_name, limit=limit, page_size=page_size, )) + self._context: Optional[WorkspaceContext] = None - def page(self, friendly_name=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + @property + def _proxy(self) -> "WorkspaceContext": """ - Retrieve a single page of WorkspaceInstance records from the API. - Request is executed immediately - - :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 + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Page of WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspacePage + :returns: WorkspaceContext for this WorkspaceInstance """ - 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 WorkspacePage(self._version, response, self._solution) + if self._context is None: + self._context = WorkspaceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of WorkspaceInstance records from the API. - Request is executed immediately + Deletes the WorkspaceInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspacePage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return WorkspacePage(self._version, response, self._solution) + return self._proxy.delete() - 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): + async def delete_async(self) -> bool: """ - Create the WorkspaceInstance + Asynchronous coroutine that deletes the WorkspaceInstance - :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 - :returns: The created WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'EventCallbackUrl': event_callback_url, - 'EventsFilter': events_filter, - 'MultiTaskEnabled': multi_task_enabled, - 'Template': template, - 'PrioritizeQueueOrder': prioritize_queue_order, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + return await self._proxy.delete_async() - return WorkspaceInstance(self._version, payload, ) - - def get(self, sid): + def delete_with_http_info(self) -> ApiResponse: """ - Constructs a WorkspaceContext + Deletes the WorkspaceInstance with HTTP info - :param sid: The SID of the resource to fetch - :returns: twilio.rest.taskrouter.v1.workspace.WorkspaceContext - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceContext + :returns: ApiResponse with success boolean, status code, and headers """ - return WorkspaceContext(self._version, sid=sid, ) + return self._proxy.delete_with_http_info() - def __call__(self, sid): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Constructs a WorkspaceContext - - :param sid: The SID of the resource to fetch - - :returns: twilio.rest.taskrouter.v1.workspace.WorkspaceContext - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceContext - """ - return WorkspaceContext(self._version, sid=sid, ) + Asynchronous coroutine that deletes the WorkspaceInstance with HTTP info - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: ApiResponse with success boolean, status code, and headers """ - return '' - + return await self._proxy.delete_with_http_info_async() -class WorkspacePage(Page): - """ """ - - def __init__(self, version, response, solution): + def fetch(self) -> "WorkspaceInstance": """ - Initialize the WorkspacePage + Fetch the WorkspaceInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.taskrouter.v1.workspace.WorkspacePage - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspacePage + :returns: The fetched WorkspaceInstance """ - super(WorkspacePage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch() - def get_instance(self, payload): + async def fetch_async(self) -> "WorkspaceInstance": """ - Build an instance of WorkspaceInstance + Asynchronous coroutine to fetch the WorkspaceInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance - """ - return WorkspaceInstance(self._version, payload, ) - - def __repr__(self): + :returns: The fetched WorkspaceInstance """ - Provide a friendly representation + return await self._proxy.fetch_async() - :returns: Machine friendly representation - :rtype: str + def fetch_with_http_info(self) -> ApiResponse: """ - return '' - + Fetch the WorkspaceInstance with HTTP info -class WorkspaceContext(InstanceContext): - """ """ - def __init__(self, version, sid): + :returns: ApiResponse with instance, status code, and headers """ - Initialize the WorkspaceContext + return self._proxy.fetch_with_http_info() - :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 + async def fetch_with_http_info_async(self) -> ApiResponse: """ - super(WorkspaceContext, self).__init__(version) + Asynchronous coroutine to fetch the WorkspaceInstance with HTTP info - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Workspaces/{sid}'.format(**self._solution) - - # Dependents - self._activities = None - self._events = None - self._tasks = None - self._task_queues = None - self._workers = None - self._workflows = None - self._statistics = None - self._real_time_statistics = None - self._cumulative_statistics = None - self._task_channels = None - - def fetch(self): - """ - Fetch the WorkspaceInstance - :returns: The fetched WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance + :returns: ApiResponse with instance, status code, and headers """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return WorkspaceInstance(self._version, payload, sid=self._solution['sid'], ) + return await self._proxy.fetch_with_http_info_async() - 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, ) + 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 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: - def delete(self): + :returns: The updated WorkspaceInstance """ - Deletes 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, + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the WorkspaceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkspaceInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) @property - def activities(self): + 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'], ) - return self._activities + return self._proxy.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'], ) - return self._events + return self._proxy.events @property - def tasks(self): + def tasks(self) -> TaskList: """ Access the tasks + """ + return self._proxy.tasks - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskList - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskList + @property + def task_channels(self) -> TaskChannelList: """ - if self._tasks is None: - self._tasks = TaskList(self._version, workspace_sid=self._solution['sid'], ) - return self._tasks + Access the task_channels + """ + return self._proxy.task_channels @property - def task_queues(self): + def task_queues(self) -> TaskQueueList: """ Access the task_queues - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList """ - if self._task_queues is None: - self._task_queues = TaskQueueList(self._version, workspace_sid=self._solution['sid'], ) - return self._task_queues + return self._proxy.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'], ) - return self._workers + return self._proxy.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'], ) - return self._workflows + return self._proxy.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 + return self._proxy.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'], - ) - return self._real_time_statistics - - @property - def cumulative_statistics(self): """ - Access the cumulative_statistics - - :returns: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsList - """ - if self._cumulative_statistics is None: - self._cumulative_statistics = WorkspaceCumulativeStatisticsList( - self._version, - workspace_sid=self._solution['sid'], - ) - return self._cumulative_statistics + return self._proxy.real_time_statistics @property - def task_channels(self): + def statistics(self) -> WorkspaceStatisticsList: """ - Access the task_channels - - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelList - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelList + Access the statistics """ - if self._task_channels is None: - self._task_channels = TaskChannelList(self._version, workspace_sid=self._solution['sid'], ) - return self._task_channels + return self._proxy.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 WorkspaceInstance(InstanceResource): - """ """ +class WorkspaceContext(InstanceContext): - class QueueOrder(object): - FIFO = "FIFO" - LIFO = "LIFO" + def __init__(self, version: Version, sid: str): + """ + Initialize the WorkspaceContext + + :param version: Version that contains the resource + :param sid: The SID of the Workspace resource to update. + """ + super().__init__(version) - 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'), + # Path Solution + self._solution = { + "sid": sid, } + self._uri = "/Workspaces/{sid}".format(**self._solution) - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + 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 - @property - def _proxy(self): + def _delete(self) -> tuple: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Internal helper for delete operation - :returns: WorkspaceContext for this WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceContext + Returns: + tuple: (success_boolean, status_code, headers) """ - if self._context is None: - self._context = WorkspaceContext(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'] + headers = values.of({}) - @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.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - @property - def date_updated(self): + def delete(self) -> bool: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + Deletes the WorkspaceInstance - @property - def default_activity_name(self): - """ - :returns: The name of the default activity - :rtype: unicode - """ - return self._properties['default_activity_name'] - @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 + :returns: True if delete succeeds, False otherwise """ - return self._properties['default_activity_sid'] + success, _, _ = self._delete() + return success - @property - def event_callback_url(self): - """ - :returns: The URL we call when an event occurs - :rtype: unicode + def delete_with_http_info(self) -> ApiResponse: """ - return self._properties['event_callback_url'] + Deletes the WorkspaceInstance and return response metadata - @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'] - @property - def friendly_name(self): + :returns: ApiResponse with success boolean, status code, and headers """ - :returns: The string that you assigned to describe the Workspace resource - :rtype: unicode - """ - return self._properties['friendly_name'] + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - @property - def multi_task_enabled(self): + async def _delete_async(self) -> tuple: """ - :returns: Whether multi-tasking is enabled - :rtype: bool - """ - return self._properties['multi_task_enabled'] + Internal async helper for delete operation - @property - def sid(self): + Returns: + tuple: (success_boolean, status_code, headers) """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - @property - def timeout_activity_name(self): - """ - :returns: The name of the timeout activity - :rtype: unicode - """ - return self._properties['timeout_activity_name'] + headers = values.of({}) - @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'] + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - @property - def prioritize_queue_order(self): + async def delete_async(self) -> bool: """ - :returns: The type of TaskQueue to prioritize when Workers are receiving Tasks from both types of TaskQueues - :rtype: WorkspaceInstance.QueueOrder + Asynchronous coroutine that deletes the WorkspaceInstance + + + :returns: True if delete succeeds, False otherwise """ - return self._properties['prioritize_queue_order'] + success, _, _ = await self._delete_async() + return success - @property - def url(self): + async def delete_with_http_info_async(self) -> ApiResponse: """ - :returns: The absolute URL of the Workspace resource - :rtype: unicode + Asynchronous coroutine that deletes the WorkspaceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers """ - return self._properties['url'] + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - @property - def links(self): + def _fetch(self) -> tuple: """ - :returns: The URLs of related resources - :rtype: unicode + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['links'] - def fetch(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WorkspaceInstance: """ Fetch the WorkspaceInstance + :returns: The fetched WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance """ - return self._proxy.fetch() + payload, _, _ = self._fetch() + 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkspaceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WorkspaceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> WorkspaceInstance: + """ + Asynchronous coroutine to fetch the WorkspaceInstance + + + :returns: The fetched WorkspaceInstance + """ + payload, _, _ = await self._fetch_async() + return WorkspaceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkspaceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WorkspaceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - return self._proxy.update( + payload, _, _ = self._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 WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the WorkspaceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( default_activity_sid=default_activity_sid, event_callback_url=event_callback_url, events_filter=events_filter, @@ -657,122 +699,916 @@ def update(self, default_activity_sid=values.unset, timeout_activity_sid=timeout_activity_sid, prioritize_queue_order=prioritize_queue_order, ) + instance = WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "DefaultActivitySid": default_activity_sid, + "EventCallbackUrl": event_callback_url, + "EventsFilter": events_filter, + "FriendlyName": friendly_name, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), + "TimeoutActivitySid": timeout_activity_sid, + "PrioritizeQueueOrder": prioritize_queue_order, + } + ) + headers = values.of({}) - def delete(self): - """ - Deletes the WorkspaceInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: True if delete succeeds, False otherwise - :rtype: bool + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._proxy.delete() + payload, _, _ = await self._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, + ) + return WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkspaceInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 """ - return self._proxy.activities + if self._activities is None: + 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 """ - return self._proxy.events + if self._events is None: + self._events = EventList( + self._version, + self._solution["sid"], + ) + return self._events @property - def tasks(self): + def tasks(self) -> TaskList: """ Access the tasks + """ + if self._tasks is None: + self._tasks = TaskList( + self._version, + self._solution["sid"], + ) + return self._tasks - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskList - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskList + @property + def task_channels(self) -> TaskChannelList: """ - return self._proxy.tasks + Access the task_channels + """ + if self._task_channels is None: + self._task_channels = TaskChannelList( + self._version, + self._solution["sid"], + ) + return self._task_channels @property - def task_queues(self): + def task_queues(self) -> TaskQueueList: """ Access the task_queues - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList """ - return self._proxy.task_queues + if self._task_queues is None: + self._task_queues = TaskQueueList( + self._version, + self._solution["sid"], + ) + return self._task_queues @property - def workers(self): + def workers(self) -> WorkerList: """ Access the workers - - :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerList """ - return self._proxy.workers + if self._workers is None: + self._workers = WorkerList( + self._version, + self._solution["sid"], + ) + return self._workers @property - def workflows(self): + def workflows(self) -> WorkflowList: """ Access the workflows + """ + if self._workflows is None: + self._workflows = WorkflowList( + self._version, + self._solution["sid"], + ) + return self._workflows - :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList + @property + def cumulative_statistics(self) -> WorkspaceCumulativeStatisticsList: """ - return self._proxy.workflows + Access the cumulative_statistics + """ + if self._cumulative_statistics is None: + self._cumulative_statistics = WorkspaceCumulativeStatisticsList( + self._version, + self._solution["sid"], + ) + return self._cumulative_statistics + + @property + def real_time_statistics(self) -> WorkspaceRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + if self._real_time_statistics is None: + self._real_time_statistics = WorkspaceRealTimeStatisticsList( + self._version, + self._solution["sid"], + ) + return self._real_time_statistics @property - def statistics(self): + def statistics(self) -> WorkspaceStatisticsList: """ Access the statistics + """ + if self._statistics is None: + self._statistics = WorkspaceStatisticsList( + self._version, + self._solution["sid"], + ) + return self._statistics - :returns: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsList + def __repr__(self) -> str: """ - return self._proxy.statistics + Provide a friendly representation - @property - def real_time_statistics(self): + :returns: Machine friendly representation """ - Access the real_time_statistics + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsList +class WorkspacePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WorkspaceInstance: """ - return self._proxy.real_time_statistics + Build an instance of WorkspaceInstance - @property - def cumulative_statistics(self): + :param payload: Payload response from the API """ - Access the cumulative_statistics - :returns: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsList + return WorkspaceInstance(self._version, payload) + + def __repr__(self) -> str: """ - return self._proxy.cumulative_statistics + Provide a friendly representation - @property - def task_channels(self): + :returns: Machine friendly representation """ - Access the task_channels + return "" - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelList - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelList + +class WorkspaceList(ListResource): + + def __init__(self, version: Version): """ - return self._proxy.task_channels + Initialize the WorkspaceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Workspaces" + + def _create( + self, + friendly_name: str, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + template: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventCallbackUrl": event_callback_url, + "EventsFilter": events_filter, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), + "Template": template, + "PrioritizeQueueOrder": prioritize_queue_order, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + template: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> WorkspaceInstance: + """ + Create the WorkspaceInstance + + :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. + :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. + :param prioritize_queue_order: + + :returns: The created WorkspaceInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + event_callback_url=event_callback_url, + events_filter=events_filter, + multi_task_enabled=multi_task_enabled, + template=template, + prioritize_queue_order=prioritize_queue_order, + ) + return WorkspaceInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the WorkspaceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. + :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. + :param prioritize_queue_order: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + event_callback_url=event_callback_url, + events_filter=events_filter, + multi_task_enabled=multi_task_enabled, + template=template, + prioritize_queue_order=prioritize_queue_order, + ) + instance = WorkspaceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventCallbackUrl": event_callback_url, + "EventsFilter": events_filter, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), + "Template": template, + "PrioritizeQueueOrder": prioritize_queue_order, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + friendly_name: str, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + template: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> WorkspaceInstance: + """ + Asynchronously create the WorkspaceInstance + + :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. + :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. + :param prioritize_queue_order: + + :returns: The created WorkspaceInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + event_callback_url=event_callback_url, + events_filter=events_filter, + multi_task_enabled=multi_task_enabled, + template=template, + prioritize_queue_order=prioritize_queue_order, + ) + return WorkspaceInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the WorkspaceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. + :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. + :param prioritize_queue_order: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + event_callback_url=event_callback_url, + events_filter=events_filter, + multi_task_enabled=multi_task_enabled, + template=template, + prioritize_queue_order=prioritize_queue_order, + ) + instance = WorkspaceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WorkspaceInstance]: + """ + Streams WorkspaceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WorkspaceInstance]: + """ + Asynchronously streams WorkspaceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams WorkspaceInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams WorkspaceInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkspaceInstance]: + """ + Lists WorkspaceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkspaceInstance]: + """ + Asynchronously lists WorkspaceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists WorkspaceInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists WorkspaceInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkspacePage: + """ + Retrieve a single page of WorkspaceInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkspaceInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkspacePage(self._version, response) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkspacePage: + """ + Asynchronously retrieve a single page of WorkspaceInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkspaceInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkspacePage(self._version, response) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with WorkspacePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WorkspacePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with WorkspacePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WorkspacePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> WorkspacePage: + """ + Retrieve a specific page of WorkspaceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkspaceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WorkspacePage(self._version, response) + + async def get_page_async(self, target_url: str) -> WorkspacePage: + """ + Asynchronously retrieve a specific page of WorkspaceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkspaceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkspacePage(self._version, response) + + def get(self, sid: str) -> WorkspaceContext: + """ + Constructs a WorkspaceContext + + :param sid: The SID of the Workspace resource to update. + """ + return WorkspaceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> WorkspaceContext: + """ + Constructs a WorkspaceContext + + :param sid: The SID of the Workspace resource to update. + """ + return WorkspaceContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 8acf7a94f5..580948aa5c 100644 --- a/twilio/rest/taskrouter/v1/workspace/activity.py +++ b/twilio/rest/taskrouter/v1/workspace/activity.py @@ -1,443 +1,1173 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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, + } - def __init__(self, version, workspace_sid): + self._context: Optional[ActivityContext] = None + + @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. + return self._proxy.delete() - :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) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ActivityInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance] + + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(friendly_name=friendly_name, available=available, page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ActivityInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, friendly_name=values.unset, available=values.unset, limit=None, - page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists ActivityInstance 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.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ActivityInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - return list(self.stream( - friendly_name=friendly_name, - available=available, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_with_http_info_async() - def page(self, friendly_name=values.unset, available=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "ActivityInstance": """ - Retrieve a single page of ActivityInstance records from the API. - Request is executed immediately + 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, - }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "ActivityInstance": + """ + Asynchronous coroutine to fetch the ActivityInstance - return ActivityPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched ActivityInstance """ - Retrieve a specific page of ActivityInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ActivityInstance with HTTP info - :returns: Page of ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ActivityInstance with HTTP info - return ActivityPage(self._version, response, self._solution) - def create(self, friendly_name, available=values.unset): + :returns: ApiResponse with instance, status code, and headers """ - Create the ActivityInstance + return await self._proxy.fetch_with_http_info_async() - :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 + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "ActivityInstance": + """ + Update the ActivityInstance - :returns: The created ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: The updated ActivityInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "ActivityInstance": """ - data = values.of({'FriendlyName': friendly_name, 'Available': available, }) + Asynchronous coroutine to update the ActivityInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :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`. - return ActivityInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + :returns: The updated ActivityInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - def get(self, sid): + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: """ - Constructs a ActivityContext + Update the ActivityInstance with HTTP info - :param sid: The SID of the resource to fetch + :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: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext + :returns: ApiResponse with instance, status code, and headers """ - return ActivityContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: """ - Constructs a ActivityContext + Asynchronous coroutine to update the ActivityInstance with HTTP info - :param sid: The SID of the resource to fetch + :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: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext + :returns: ApiResponse with instance, status code, and headers """ - return ActivityContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_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 ActivityPage(Page): - """ """ +class ActivityContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ - Initialize the ActivityPage - - :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 + Initialize the ActivityContext - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityPage - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityPage + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Activity resources to update. + :param sid: The SID of the Activity resource to update. """ - super(ActivityPage, 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}/Activities/{sid}".format( + **self._solution + ) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of ActivityInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance + def delete(self) -> bool: """ - return ActivityInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + Deletes the ActivityInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the ActivityInstance and return response metadata -class ActivityContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, workspace_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the ActivityContext + Internal async helper for delete operation - :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: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext + async def delete_async(self) -> bool: """ - super(ActivityContext, self).__init__(version) + Asynchronous coroutine that deletes the ActivityInstance - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/Activities/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ActivityInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ActivityInstance: """ Fetch the ActivityInstance + :returns: The fetched ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ActivityInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ActivityInstance: + """ + Asynchronous coroutine to fetch the ActivityInstance + + :returns: The fetched ActivityInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ActivityInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._update(friendly_name=friendly_name) + return ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the ActivityInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Accept"] = "application/json" + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ActivityInstance: + """ + Asynchronous coroutine to update the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: The updated ActivityInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) 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_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: """ - Deletes the ActivityInstance + Asynchronous coroutine to update the ActivityInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 get_instance(self, payload: Dict[str, Any]) -> ActivityInstance: + """ + Build an instance of ActivityInstance + + :param payload: Payload response from the API + """ + + return ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation - def __init__(self, version, payload, workspace_sid, sid=None): + :returns: Machine friendly representation """ - Initialize the ActivityInstance + return "" + - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance +class ActivityList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): """ - super(ActivityInstance, self).__init__(version) + Initialize the ActivityList - # 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'), + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Activity resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, } + self._uri = "/Workspaces/{workspace_sid}/Activities".format(**self._solution) - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: ActivityContext for this ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> ActivityInstance: """ - if self._context is None: - self._context = ActivityContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the ActivityInstance - @property - def account_sid(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 SID of the Account that created the resource - :rtype: unicode + payload, _, _ = self._create(friendly_name=friendly_name, available=available) + return ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def create_with_http_info( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> ApiResponse: """ - return self._properties['account_sid'] + Create the ActivityInstance and return response metadata - @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: ApiResponse with instance, status code, and headers """ - :returns: Whether the Worker should be eligible to receive a Task when it occupies the Activity - :rtype: bool + payload, status_code, headers = self._create( + friendly_name=friendly_name, available=available + ) + instance = ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> tuple: """ - return self._properties['available'] + Internal async helper for create operation - @property - def date_created(self): + Returns: + tuple: (payload, status_code, headers) """ - :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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> ActivityInstance: """ - return self._properties['date_created'] + Asynchronously create the ActivityInstance - @property - def date_updated(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 last updated - :rtype: datetime + payload, _, _ = await self._create_async( + friendly_name=friendly_name, available=available + ) + return ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_with_http_info_async( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously create the ActivityInstance and return response metadata - @property - def friendly_name(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: ApiResponse with instance, status code, and headers """ - :returns: The string that you assigned to describe the Activity resource - :rtype: unicode + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, available=available + ) + instance = ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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['friendly_name'] + 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 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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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( + 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['sid'] + 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 workspace_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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 Activity - :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 stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['workspace_sid'] + Streams ActivityInstance and returns headers from first page - @property - def url(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The absolute URL of the Activity resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, + available=available, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['url'] + Asynchronously streams ActivityInstance and returns headers from first page - def fetch(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: tuple of (generator, status_code, headers) where generator yields instances """ - Fetch the ActivityInstance + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, + available=available, + page_size=limits["page_size"], + ) - :returns: The fetched ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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._proxy.fetch() + 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) - def update(self, friendly_name=values.unset): + :returns: list that will contain up to limit results """ - Update the ActivityInstance - :param unicode friendly_name: A string to describe the Activity resource + return list( + self.stream( + friendly_name=friendly_name, + available=available, + limit=limit, + page_size=page_size, + ) + ) - :returns: The updated ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance + 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]: """ - return self._proxy.update(friendly_name=friendly_name, ) + 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) - def delete(self): + :returns: list that will contain up to limit results """ - Deletes the ActivityInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + available=available, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._proxy.delete() + Lists ActivityInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + available=available, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ActivityInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + available=available, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ActivityPage: + """ + Retrieve a single page of ActivityInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Activity resources to read. + :param available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ActivityInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Available": available, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ActivityPage(self._version, response, solution=self._solution) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ActivityPage: + """ + Asynchronously retrieve a single page of ActivityInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Activity resources to read. + :param available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ActivityInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Available": available, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ActivityPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ActivityPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ActivityPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ActivityPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ActivityPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ActivityPage: + """ + Retrieve a specific page of ActivityInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ActivityInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ActivityPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ActivityPage: + """ + Asynchronously retrieve a specific page of ActivityInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ActivityInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ActivityPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> ActivityContext: + """ + Constructs a ActivityContext + + :param sid: The SID of the Activity resource to update. + """ + return ActivityContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ActivityContext: + """ + Constructs a ActivityContext + + :param sid: The SID of the Activity resource to update. + """ + return ActivityContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 554bb47979..73cc6f2ebf 100644 --- a/twilio/rest/taskrouter/v1/workspace/event.py +++ b/twilio/rest/taskrouter/v1/workspace/event.py @@ -1,530 +1,1101 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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 + 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 Event + :returns: EventContext for this EventInstance + """ + if self._context is None: + self._context = EventContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.taskrouter.v1.workspace.event.EventList - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventList + def fetch(self) -> "EventInstance": """ - super(EventList, self).__init__(version) + Fetch the EventInstance - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/Events'.format(**self._solution) - 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): + :returns: The fetched EventInstance """ - Streams EventInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param datetime end_date: Only include 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) + return self._proxy.fetch() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.event.EventInstance] + async def fetch_async(self) -> "EventInstance": """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine to fetch the EventInstance - page = self.page( - end_date=end_date, - event_type=event_type, - minutes=minutes, - reservation_sid=reservation_sid, - start_date=start_date, - task_queue_sid=task_queue_sid, - task_sid=task_sid, - worker_sid=worker_sid, - workflow_sid=workflow_sid, - task_channel=task_channel, - sid=sid, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched EventInstance + """ + return await self._proxy.fetch_async() - 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Lists EventInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Fetch the EventInstance with HTTP info - :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] + :returns: ApiResponse with instance, status code, and headers """ - 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, - )) + return self._proxy.fetch_with_http_info() - 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of EventInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the EventInstance with HTTP info - :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, ) - - return EventPage(self._version, response, self._solution) - - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of EventInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page - - :returns: Page of EventInstance - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventPage + def __repr__(self) -> str: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return EventPage(self._version, response, self._solution) + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a EventContext + 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.event.EventContext - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext +class EventContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): """ - return EventContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + Initialize the EventContext - def __call__(self, sid): + :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. """ - Constructs a EventContext + 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}/Events/{sid}".format(**self._solution) - :returns: twilio.rest.taskrouter.v1.workspace.event.EventContext - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext + def _fetch(self) -> tuple: """ - return EventContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + Internal helper for fetch operation - def __repr__(self): + Returns: + tuple: (payload, status_code, headers) """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers = values.of({}) + headers["Accept"] = "application/json" -class EventPage(Page): - """ """ + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> EventInstance: """ - Initialize the EventPage + Fetch the EventInstance - :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 - :returns: twilio.rest.taskrouter.v1.workspace.event.EventPage - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventPage + :returns: The fetched EventInstance """ - super(EventPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = self._fetch() + return EventInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - def get_instance(self, payload): + def fetch_with_http_info(self) -> ApiResponse: """ - Build an instance of EventInstance + Fetch the EventInstance and return response metadata - :param dict payload: Payload response from the API - :returns: twilio.rest.taskrouter.v1.workspace.event.EventInstance - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance + :returns: ApiResponse with instance, status code, and headers """ - return EventInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + payload, status_code, headers = self._fetch() + instance = EventInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -class EventContext(InstanceContext): - """ """ - - def __init__(self, version, workspace_sid, sid): - """ - Initialize the EventContext + headers["Accept"] = "application/json" - :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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: twilio.rest.taskrouter.v1.workspace.event.EventContext - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext + async def fetch_async(self) -> EventInstance: """ - super(EventContext, self).__init__(version) + Asynchronous coroutine to fetch the EventInstance - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/Events/{sid}'.format(**self._solution) - def fetch(self): + :returns: The fetched EventInstance """ - Fetch the EventInstance + payload, _, _ = await self._fetch_async() + return EventInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - :returns: The fetched EventInstance - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance + async def fetch_with_http_info_async(self) -> ApiResponse: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronous coroutine to fetch the EventInstance and return response metadata - return EventInstance( + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EventInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 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'), - } - - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } +class EventPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: """ - 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 EventInstance - :returns: EventContext for this EventInstance - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = EventContext( - self._version, - workspace_sid=self._solution['workspace_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'] + return EventInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) - @property - def actor_sid(self): - """ - :returns: The SID of the resource that triggered the event - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['actor_sid'] + Provide a friendly representation - @property - def actor_type(self): - """ - :returns: The type of resource that triggered the event - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['actor_type'] + return "" - @property - def actor_url(self): - """ - :returns: The absolute URL of the resource that triggered the event - :rtype: unicode - """ - return self._properties['actor_url'] - @property - def description(self): - """ - :returns: A description of the event - :rtype: unicode - """ - return self._properties['description'] +class EventList(ListResource): - @property - def event_data(self): + def __init__(self, version: Version, workspace_sid: str): """ - :returns: Data about the event - :rtype: dict - """ - return self._properties['event_data'] + Initialize the EventList - @property - def event_date(self): - """ - :returns: The time the event was sent - :rtype: datetime - """ - return self._properties['event_date'] + :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. - @property - def event_date_ms(self): - """ - :returns: The time the event was sent in milliseconds - :rtype: unicode """ - return self._properties['event_date_ms'] + super().__init__(version) - @property - def event_type(self): - """ - :returns: The identifier for the event - :rtype: unicode + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Events".format(**self._solution) + + def stream( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EventInstance]: """ - return self._properties['event_type'] + 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. - @property - def resource_sid(self): - """ - :returns: The SID of the object the event is most relevant to - :rtype: unicode - """ - return self._properties['resource_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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 resource_type(self): + :returns: Generator that will yield up to limit results """ - :returns: The type of object the event is most relevant to - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = self.page( + end_date=end_date, + event_type=event_type, + minutes=minutes, + reservation_sid=reservation_sid, + start_date=start_date, + task_queue_sid=task_queue_sid, + task_sid=task_sid, + worker_sid=worker_sid, + workflow_sid=workflow_sid, + task_channel=task_channel, + sid=sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EventInstance]: + """ + Asynchronously streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['resource_type'] + 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"], + ) - @property - def resource_url(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams EventInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The URL of the resource the event is most relevant to - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams EventInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['resource_url'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) - @property - def sid(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + end_date=end_date, + event_type=event_type, + minutes=minutes, + reservation_sid=reservation_sid, + start_date=start_date, + task_queue_sid=task_queue_sid, + task_sid=task_sid, + worker_sid=worker_sid, + workflow_sid=workflow_sid, + task_channel=task_channel, + sid=sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Asynchronously lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + end_date=end_date, + event_type=event_type, + minutes=minutes, + reservation_sid=reservation_sid, + start_date=start_date, + task_queue_sid=task_queue_sid, + task_sid=task_sid, + worker_sid=worker_sid, + workflow_sid=workflow_sid, + task_channel=task_channel, + sid=sid, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists EventInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists EventInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['sid'] + Retrieve a single page of EventInstance records from the API. + Request is executed immediately - @property - def source(self): + :param end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param event_type: The type of Events to read. Returns only Events of the type specified. + :param minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param sid: The SID of the Event resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance """ - :returns: Where the Event originated - :rtype: unicode + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "EventType": event_type, + "Minutes": minutes, + "ReservationSid": reservation_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskQueueSid": task_queue_sid, + "TaskSid": task_sid, + "WorkerSid": worker_sid, + "WorkflowSid": workflow_sid, + "TaskChannel": task_channel, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, solution=self._solution) + + async def page_async( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Asynchronously retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param event_type: The type of Events to read. Returns only Events of the type specified. + :param minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param sid: The SID of the Event resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance """ - return self._properties['source'] + 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 source_ip_address(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 EventPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param event_type: The type of Events to read. Returns only Events of the type specified. + :param minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param sid: The SID of the Event resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventPage, status code, and headers + """ + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "EventType": event_type, + "Minutes": minutes, + "ReservationSid": reservation_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskQueueSid": task_queue_sid, + "TaskSid": task_sid, + "WorkerSid": worker_sid, + "WorkflowSid": workflow_sid, + "TaskChannel": task_channel, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param event_type: The type of Events to read. Returns only Events of the type specified. + :param minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param sid: The SID of the Event resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventPage, status code, and headers + """ + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "EventType": event_type, + "Minutes": minutes, + "ReservationSid": reservation_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskQueueSid": task_queue_sid, + "TaskSid": task_sid, + "WorkerSid": worker_sid, + "WorkflowSid": workflow_sid, + "TaskChannel": task_channel, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> EventPage: """ - :returns: The IP from which the Event originated - :rtype: unicode + Retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance """ - return self._properties['source_ip_address'] + response = self._version.domain.twilio.request("GET", target_url) + return EventPage(self._version, response, solution=self._solution) - @property - def url(self): + async def get_page_async(self, target_url: str) -> EventPage: """ - :returns: The absolute URL of the Event resource - :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, solution=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 c9ffbdd92b..c03fe1abb9 100644 --- a/twilio/rest/taskrouter/v1/workspace/task/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/task/__init__.py @@ -1,689 +1,1891 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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") - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskList - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskList - """ - super(TaskList, self).__init__(version) + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/Tasks'.format(**self._solution) + self._context: Optional[TaskContext] = None - 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): + @property + def _proxy(self) -> "TaskContext": """ - 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. + 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 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) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.task.TaskInstance] + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the TaskInstance - 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'], - ) + :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). - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + if_match=if_match, + ) - 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 delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: """ - Retrieve a single page of TaskInstance records from the API. - Request is executed immediately + Deletes the TaskInstance with HTTP info - :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 + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). - :returns: Page of TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskPage + :returns: ApiResponse with success boolean, status code, and headers """ - 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, ) - - return TaskPage(self._version, response, self._solution) + return self._proxy.delete_with_http_info( + if_match=if_match, + ) - def get_page(self, target_url): + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: """ - Retrieve a specific page of TaskInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the TaskInstance with HTTP info - :param str target_url: API-generated URL for the requested results page + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). - :returns: Page of TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskPage + :returns: ApiResponse with success boolean, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.delete_with_http_info_async( + if_match=if_match, ) - return TaskPage(self._version, response, self._solution) - - def create(self, timeout=values.unset, priority=values.unset, - task_channel=values.unset, workflow_sid=values.unset, - attributes=values.unset): + def fetch(self) -> "TaskInstance": """ - Create the TaskInstance + Fetch 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 - :returns: The created TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance + :returns: The fetched TaskInstance """ - data = values.of({ - 'Timeout': timeout, - 'Priority': priority, - 'TaskChannel': task_channel, - 'WorkflowSid': workflow_sid, - 'Attributes': attributes, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return TaskInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + return self._proxy.fetch() - def get(self, sid): + async def fetch_async(self) -> "TaskInstance": """ - Constructs a TaskContext + Asynchronous coroutine to fetch the TaskInstance - :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 """ - return TaskContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + return await self._proxy.fetch_async() - def __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a TaskContext - - :param sid: The SID of the resource to fetch + Fetch the TaskInstance with HTTP info - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskContext - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskContext - """ - return TaskContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) - def __repr__(self): + :returns: ApiResponse with instance, status code, and headers """ - Provide a friendly representation + return self._proxy.fetch_with_http_info() - :returns: Machine friendly representation - :rtype: str + async def fetch_with_http_info_async(self) -> ApiResponse: """ - return '' + Asynchronous coroutine to fetch the TaskInstance with HTTP info -class TaskPage(Page): - """ """ + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() - def __init__(self, version, response, solution): + 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": """ - Initialize the TaskPage + Update the TaskInstance - :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 + :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.TaskPage - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskPage + :returns: The updated TaskInstance """ - super(TaskPage, self).__init__(version, response) + 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, + ) - # Path Solution - self._solution = solution + 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. - def get_instance(self, payload): + :returns: The updated TaskInstance """ - Build an instance of TaskInstance + return await self._proxy.update_async( + if_match=if_match, + attributes=attributes, + assignment_status=assignment_status, + reason=reason, + priority=priority, + task_channel=task_channel, + virtual_start_time=virtual_start_time, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the TaskInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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 dict payload: Payload response from the API + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TaskInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + if_match=if_match, + attributes=attributes, + assignment_status=assignment_status, + reason=reason, + priority=priority, + task_channel=task_channel, + virtual_start_time=virtual_start_time, + ) - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance + @property + def reservations(self) -> ReservationList: + """ + Access the reservations """ - return TaskInstance(self._version, payload, workspace_sid=self._solution['workspace_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 TaskContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid, sid): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ Initialize the TaskContext - :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 + :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(TaskContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/Tasks/{sid}'.format(**self._solution) + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Tasks/{sid}".format(**self._solution) - # Dependents - self._reservations = None + self._reservations: Optional[ReservationList] = None - def fetch(self): + def _delete(self, if_match: Union[str, object] = values.unset) -> tuple: """ - Fetch the TaskInstance + Internal helper for delete operation - :returns: The fetched TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return TaskInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + headers = values.of( + { + "If-Match": if_match, + } ) - def update(self, attributes=values.unset, assignment_status=values.unset, - reason=values.unset, priority=values.unset, - task_channel=values.unset): - """ - 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 - - :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, - }) + headers = values.of({}) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return TaskInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers ) - def delete(self): + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ Deletes the TaskInstance + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + success, _, _ = self._delete(if_match=if_match) + return success - @property - def reservations(self): + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: """ - Access the reservations + Deletes the TaskInstance and return response metadata - :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'], - ) - return self._reservations + :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). - def __repr__(self): + :returns: ApiResponse with success boolean, status code, and headers """ - Provide a friendly representation + success, status_code, headers = self._delete(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, headers=headers) - :returns: Machine friendly representation - :rtype: str + async def _delete_async(self, if_match: Union[str, object] = values.unset) -> tuple: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class TaskInstance(InstanceResource): - """ """ + Internal async helper for delete operation - class Status(object): - PENDING = "pending" - RESERVED = "reserved" - ASSIGNED = "assigned" - CANCELED = "canceled" - COMPLETED = "completed" - WRAPPING = "wrapping" + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "If-Match": if_match, + } + ) - 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'), - } + headers = values.of({}) - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - @property - def _proxy(self): + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: """ - 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 that deletes the TaskInstance - :returns: TaskContext for this TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskContext - """ - if self._context is None: - self._context = TaskContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - return self._context + :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). - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: True if delete succeeds, False otherwise """ - return self._properties['account_sid'] + success, _, _ = await self._delete_async(if_match=if_match) + return success - @property - def age(self): + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: """ - :returns: The number of seconds since the Task was created - :rtype: unicode - """ - return self._properties['age'] + Asynchronous coroutine that deletes the TaskInstance and return response metadata - @property - def assignment_status(self): - """ - :returns: The current status of the Task's assignment - :rtype: TaskInstance.Status - """ - return self._properties['assignment_status'] + :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). - @property - def attributes(self): - """ - :returns: The JSON string with custom attributes of the work - :rtype: unicode + :returns: ApiResponse with success boolean, status code, and headers """ - return self._properties['attributes'] + success, status_code, headers = await self._delete_async(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, headers=headers) - @property - def addons(self): - """ - :returns: An object that contains the addon data for all installed addons - :rtype: unicode + def _fetch(self) -> tuple: """ - return self._properties['addons'] + Internal helper for fetch operation - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Returns: + tuple: (payload, status_code, headers) """ - 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'] + headers = values.of({}) - @property - def task_queue_entered_date(self): - """ - :returns: The ISO 8601 date and time in GMT when the Task entered the TaskQueue. - :rtype: datetime - """ - return self._properties['task_queue_entered_date'] + headers["Accept"] = "application/json" - @property - def priority(self): - """ - :returns: Retrieve the list of all Tasks in the Workspace with the specified priority - :rtype: unicode - """ - return self._properties['priority'] + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - @property - def reason(self): - """ - :returns: The reason the Task was canceled or completed - :rtype: unicode + def fetch(self) -> TaskInstance: """ - return self._properties['reason'] + Fetch the TaskInstance - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - @property - def task_queue_sid(self): - """ - :returns: The SID of the TaskQueue - :rtype: unicode + :returns: The fetched TaskInstance """ - return self._properties['task_queue_sid'] + payload, _, _ = self._fetch() + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - @property - def task_queue_friendly_name(self): + def fetch_with_http_info(self) -> ApiResponse: """ - :returns: The friendly name of the TaskQueue - :rtype: unicode - """ - return self._properties['task_queue_friendly_name'] + Fetch the TaskInstance and return response metadata - @property - def task_channel_sid(self): - """ - :returns: The SID of the TaskChannel - :rtype: unicode - """ - return self._properties['task_channel_sid'] - @property - def task_channel_unique_name(self): - """ - :returns: The unique name of the TaskChannel - :rtype: unicode + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['task_channel_unique_name'] + payload, status_code, headers = self._fetch() + instance = TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def timeout(self): + async def _fetch_async(self) -> tuple: """ - :returns: The amount of time in seconds that the Task is allowed to live - :rtype: unicode - """ - return self._properties['timeout'] + Internal async helper for fetch operation - @property - def workflow_sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The SID of the Workflow that is controlling the Task - :rtype: unicode - """ - 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 - """ - return self._properties['workflow_friendly_name'] + headers = values.of({}) - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace that contains the Task - :rtype: unicode - """ - return self._properties['workspace_sid'] + headers["Accept"] = "application/json" - @property - def url(self): - """ - :returns: The absolute URL of the Task resource - :rtype: unicode - """ - return self._properties['url'] + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - @property - def links(self): + async def fetch_async(self) -> TaskInstance: """ - :returns: The URLs of related resources - :rtype: unicode - """ - return self._properties['links'] + Asynchronous coroutine to fetch the TaskInstance - def fetch(self): - """ - Fetch the TaskInstance :returns: The fetched TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance """ - return self._proxy.fetch() + payload, _, _ = await self._fetch_async() + return TaskInstance( + self._version, + payload, + 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the TaskInstance + Asynchronous coroutine to fetch the TaskInstance and return response metadata - :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 - :returns: The updated TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.update( + payload, status_code, headers = await self._fetch_async() + instance = TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> TaskInstance: + """ + Update the TaskInstance + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: The updated TaskInstance + """ + payload, _, _ = self._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, + ) + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the TaskInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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({}) - def delete(self): - """ - Deletes the TaskInstance + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match - :returns: True if delete succeeds, False otherwise - :rtype: bool + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> TaskInstance: + """ + Asynchronous coroutine to update the TaskInstance + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: The updated TaskInstance """ - return self._proxy.delete() + payload, _, _ = await self._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, + ) + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TaskInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def reservations(self): + def reservations(self) -> ReservationList: """ Access the reservations + """ + if self._reservations is None: + self._reservations = ReservationList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._reservations - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationList - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationList + def __repr__(self) -> str: """ - return self._proxy.reservations + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TaskPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TaskInstance: + """ + Build an instance of TaskInstance + + :param payload: Payload response from the API + """ + + return TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TaskList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the TaskList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Tasks to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Tasks".format(**self._solution) + + def _create( + self, + timeout: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ignore_capacity: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + timeout: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ignore_capacity: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ) -> TaskInstance: + """ + Create the TaskInstance + + :param timeout: The amount of time in seconds the new task can live before being assigned. Can be up to a maximum of 2 weeks (1,209,600 seconds). The default value is 24 hours (86,400 seconds). On timeout, the `task.canceled` event will fire with description `Task TTL Exceeded`. + :param priority: The priority to assign the new task and override the default. When supplied, the new Task will have this priority unless it matches a Workflow Target with a Priority set. When not supplied, the new Task will have the priority of the matching Workflow Target. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel by passing either its `unique_name` or `sid`. Default value is `default`. + :param workflow_sid: The SID of the Workflow that you would like to handle routing for the new Task. If there is only one Workflow defined for the Workspace that you are posting the new task to, this parameter is optional. + :param attributes: A JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. + :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future or before the year of 1900. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :param task_queue_sid: The SID of the TaskQueue in which the Task belongs + + :returns: The created TaskInstance + """ + payload, _, _ = self._create( + timeout=timeout, + priority=priority, + task_channel=task_channel, + workflow_sid=workflow_sid, + attributes=attributes, + virtual_start_time=virtual_start_time, + routing_target=routing_target, + ignore_capacity=ignore_capacity, + task_queue_sid=task_queue_sid, + ) + return TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the TaskInstance and return response metadata + + :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 JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. + :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future or before the year of 1900. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :param task_queue_sid: The SID of the TaskQueue in which the Task belongs + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + timeout=timeout, + priority=priority, + task_channel=task_channel, + workflow_sid=workflow_sid, + attributes=attributes, + virtual_start_time=virtual_start_time, + routing_target=routing_target, + ignore_capacity=ignore_capacity, + task_queue_sid=task_queue_sid, + ) + instance = TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. + :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future or before the year of 1900. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :param task_queue_sid: The SID of the TaskQueue in which the Task belongs + + :returns: The created TaskInstance + """ + payload, _, _ = await self._create_async( + timeout=timeout, + priority=priority, + task_channel=task_channel, + workflow_sid=workflow_sid, + attributes=attributes, + virtual_start_time=virtual_start_time, + routing_target=routing_target, + ignore_capacity=ignore_capacity, + task_queue_sid=task_queue_sid, + ) + return TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the TaskInstance and return response metadata + + :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 JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. + :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future or before the year of 1900. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :param task_queue_sid: The SID of the TaskQueue in which the Task belongs + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + timeout=timeout, + priority=priority, + task_channel=task_channel, + workflow_sid=workflow_sid, + attributes=attributes, + virtual_start_time=virtual_start_time, + routing_target=routing_target, + ignore_capacity=ignore_capacity, + task_queue_sid=task_queue_sid, + ) + instance = TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TaskInstance]: + """ + Streams TaskInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TaskInstance]: + """ + Asynchronously streams TaskInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams TaskInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams TaskInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskInstance]: + """ + Lists TaskInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskInstance]: + """ + Asynchronously lists TaskInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists TaskInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists TaskInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskPage: + """ + Retrieve a single page of TaskInstance records from the API. + Request is executed immediately + + :param priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskInstance + """ + data = values.of( + { + "Priority": priority, + "AssignmentStatus": serialize.map(assignment_status, lambda e: e), + "WorkflowSid": workflow_sid, + "WorkflowName": workflow_name, + "TaskQueueSid": task_queue_sid, + "TaskQueueName": task_queue_name, + "EvaluateTaskAttributes": evaluate_task_attributes, + "RoutingTarget": routing_target, + "Ordering": ordering, + "HasAddons": serialize.boolean_to_string(has_addons), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskPage(self._version, response, solution=self._solution) + + async def page_async( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskPage: + """ + Asynchronously retrieve a single page of TaskInstance records from the API. + Request is executed immediately + + :param priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskInstance + """ + data = values.of( + { + "Priority": priority, + "AssignmentStatus": serialize.map(assignment_status, lambda e: e), + "WorkflowSid": workflow_sid, + "WorkflowName": workflow_name, + "TaskQueueSid": task_queue_sid, + "TaskQueueName": task_queue_name, + "EvaluateTaskAttributes": evaluate_task_attributes, + "RoutingTarget": routing_target, + "Ordering": ordering, + "HasAddons": serialize.boolean_to_string(has_addons), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with TaskPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TaskPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with TaskPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TaskPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> TaskPage: + """ + Retrieve a specific page of TaskInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TaskPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> TaskPage: + """ + Asynchronously retrieve a specific page of TaskInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TaskPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> TaskContext: + """ + Constructs a TaskContext + + :param sid: The SID of the Task resource to update. + """ + return TaskContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> TaskContext: + """ + Constructs a TaskContext + + :param sid: The SID of the Task resource to update. + """ + return TaskContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 5dde6523ad..c6a845b47b 100644 --- a/twilio/rest/taskrouter/v1/workspace/task/reservation.py +++ b/twilio/rest/taskrouter/v1/workspace/task/reservation.py @@ -1,434 +1,29 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'task_sid': task_sid, } - self._uri = '/Workspaces/{workspace_sid}/Tasks/{task_sid}/Reservations'.format(**self._solution) - - def stream(self, reservation_status=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. - - :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) - - :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) - - page = self.page(reservation_status=reservation_status, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, reservation_status=values.unset, limit=None, page_size=None): - """ - 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) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance] - """ - return list(self.stream(reservation_status=reservation_status, limit=limit, page_size=page_size, )) - - def page(self, reservation_status=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of ReservationInstance records from the API. - Request is executed immediately - - :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 - """ - 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) - - def get_page(self, target_url): - """ - Retrieve a specific page of ReservationInstance records from the API. - Request is executed immediately - - :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 - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ReservationPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a ReservationContext - - :param sid: The SID of the TaskReservation resource to fetch - - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext - """ - return ReservationContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_sid=self._solution['task_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a ReservationContext - - :param sid: The SID of the TaskReservation resource to fetch - - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext - """ - return ReservationContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_sid=self._solution['task_sid'], - sid=sid, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ReservationPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - 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 - - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationPage - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationPage - """ - super(ReservationPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of 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 - """ - return ReservationInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - task_sid=self._solution['task_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ReservationContext(InstanceContext): - """ """ - - def __init__(self, version, workspace_sid, task_sid, sid): - """ - Initialize the ReservationContext - - :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 - - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext - """ - super(ReservationContext, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'task_sid': task_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/Tasks/{task_sid}/Reservations/{sid}'.format(**self._solution) - - def fetch(self): - """ - 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, ) - - return ReservationInstance( - self._version, - payload, - 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): - """ - 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 - - :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, ) - - return ReservationInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - task_sid=self._solution['task_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 ReservationInstance(InstanceResource): - """ """ - - class Status(object): - PENDING = "pending" - ACCEPTED = "accepted" - REJECTED = "rejected" - TIMEOUT = "timeout" - CANCELED = "canceled" - RESCINDED = "rescinded" - WRAPPING = "wrapping" - COMPLETED = "completed" class CallStatus(object): INITIATED = "initiated" @@ -445,253 +40,251 @@ class ConferenceEvent(object): HOLD = "hold" SPEAKER = "speaker" + class Status(object): + PENDING = "pending" + ACCEPTED = "accepted" + REJECTED = "rejected" + TIMEOUT = "timeout" + CANCELED = "canceled" + RESCINDED = "rescinded" + WRAPPING = "wrapping" + COMPLETED = "completed" + class SupervisorMode(object): MONITOR = "monitor" WHISPER = "whisper" BARGE = "barge" - def __init__(self, version, payload, workspace_sid, task_sid, sid=None): - """ - Initialize the ReservationInstance - - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance - """ - super(ReservationInstance, 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')), - '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'), - } + """ + :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") - # Context - self._context = None self._solution = { - 'workspace_sid': workspace_sid, - 'task_sid': task_sid, - 'sid': sid or self._properties['sid'], + "workspace_sid": workspace_sid, + "task_sid": task_sid, + "sid": sid or self.sid, } + self._context: Optional[ReservationContext] = None + @property - def _proxy(self): + def _proxy(self) -> "ReservationContext": """ Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + performing various actions. All instance actions are proxied to the context :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'], + workspace_sid=self._solution["workspace_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): + def fetch(self) -> "ReservationInstance": """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + Fetch the ReservationInstance - @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 reservation_status(self): - """ - :returns: The current status of the reservation - :rtype: ReservationInstance.Status + :returns: The fetched ReservationInstance """ - return self._properties['reservation_status'] + return self._proxy.fetch() - @property - def sid(self): + async def fetch_async(self) -> "ReservationInstance": """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Asynchronous coroutine to fetch the ReservationInstance - @property - def task_sid(self): - """ - :returns: The SID of the reserved Task resource - :rtype: unicode - """ - return self._properties['task_sid'] - @property - def worker_name(self): - """ - :returns: The friendly_name of the Worker that is reserved - :rtype: unicode + :returns: The fetched ReservationInstance """ - return self._properties['worker_name'] + return await self._proxy.fetch_async() - @property - def worker_sid(self): + def fetch_with_http_info(self) -> ApiResponse: """ - :returns: The SID of the reserved Worker resource - :rtype: unicode - """ - return self._properties['worker_sid'] + Fetch the ReservationInstance with HTTP info - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace that this task is contained within. - :rtype: unicode - """ - return self._properties['workspace_sid'] - @property - def url(self): - """ - :returns: The absolute URL of the TaskReservation reservation - :rtype: unicode + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['url'] + return self._proxy.fetch_with_http_info() - @property - def links(self): - """ - :returns: The URLs of related resources - :rtype: unicode + async def fetch_with_http_info_async(self) -> ApiResponse: """ - return self._properties['links'] + Asynchronous coroutine to fetch the ReservationInstance with HTTP info - def fetch(self): - """ - Fetch the ReservationInstance - :returns: The fetched ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.fetch() - - 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): + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> "ReservationInstance": """ Update the ReservationInstance - :param 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 + :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 """ return self._proxy.update( + if_match=if_match, reservation_status=reservation_status, worker_activity_sid=worker_activity_sid, instruction=instruction, @@ -745,14 +338,2299 @@ def update(self, reservation_status=values.unset, supervisor=supervisor, end_conference_on_customer_exit=end_conference_on_customer_exit, beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> "ReservationInstance": + """ + Asynchronous coroutine to update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + return await self._proxy.update_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ReservationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ReservationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ReservationContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, task_sid: str, sid: str): + """ + Initialize the ReservationContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskReservation resources to update. + :param task_sid: The SID of the reserved Task resource with the TaskReservation resources to update. + :param sid: The SID of the TaskReservation resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_sid": task_sid, + "sid": sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Tasks/{task_sid}/Reservations/{sid}".format( + **self._solution + ) + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ReservationInstance: + """ + Fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + payload, _, _ = self._fetch() + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ReservationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ReservationInstance: + """ + Asynchronous coroutine to fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + payload, _, _ = await self._fetch_async() + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ReservationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + payload, _, _ = self._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, + ) + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ReservationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Asynchronous coroutine to update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + payload, _, _ = await self._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, + ) + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ReservationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 ReservationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ReservationInstance: + """ + Build an instance of ReservationInstance + + :param payload: Payload response from the API + """ + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ReservationList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, task_sid: str): + """ + Initialize the ReservationList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskReservation resources to read. + :param task_sid: The SID of the reserved Task resource with the TaskReservation resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_sid": task_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Tasks/{task_sid}/Reservations".format( + **self._solution + ) + + def stream( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ReservationInstance]: + """ + Streams ReservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + reservation_status=reservation_status, + worker_sid=worker_sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ReservationInstance]: + """ + Asynchronously streams ReservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + reservation_status=reservation_status, + worker_sid=worker_sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams ReservationInstance and returns headers from first page + + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + reservation_status=reservation_status, + worker_sid=worker_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams ReservationInstance and returns headers from first page + + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + reservation_status=reservation_status, + worker_sid=worker_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ReservationInstance]: + """ + Lists ReservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + reservation_status=reservation_status, + worker_sid=worker_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ReservationInstance]: + """ + Asynchronously lists ReservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + reservation_status=reservation_status, + worker_sid=worker_sid, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists ReservationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + reservation_status=reservation_status, + worker_sid=worker_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists ReservationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + reservation_status=reservation_status, + worker_sid=worker_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ReservationPage: + """ + Retrieve a single page of ReservationInstance records from the API. + Request is executed immediately + + :param reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param worker_sid: The SID of the reserved Worker resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ReservationInstance + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerSid": worker_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, solution=self._solution) + + async def page_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ReservationPage: + """ + Asynchronously retrieve a single page of ReservationInstance records from the API. + Request is executed immediately + + :param reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param worker_sid: The SID of the reserved Worker resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ReservationInstance + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerSid": worker_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ReservationPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ReservationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ReservationPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ReservationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ReservationPage: + """ + Retrieve a specific page of ReservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ReservationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ReservationPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ReservationPage: + """ + Asynchronously retrieve a specific page of ReservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ReservationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ReservationPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> ReservationContext: + """ + Constructs a ReservationContext + + :param sid: The SID of the TaskReservation resource to update. + """ + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ReservationContext: + """ + Constructs a ReservationContext + + :param sid: The SID of the TaskReservation resource to update. + """ + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=sid, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 470b9848e9..ea27998d19 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_channel.py +++ b/twilio/rest/taskrouter/v1/workspace/task_channel.py @@ -1,457 +1,1187 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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") - def __init__(self, version, workspace_sid): + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + + self._context: Optional[TaskChannelContext] = None + + @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. + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TaskChannelInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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: 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TaskChannelInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists TaskChannelInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TaskChannelInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "TaskChannelInstance": """ - Retrieve a single page of TaskChannelInstance records from the API. - Request is executed immediately + 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, }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "TaskChannelInstance": + """ + Asynchronous coroutine to fetch the TaskChannelInstance - return TaskChannelPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched TaskChannelInstance """ - Retrieve a specific page of TaskChannelInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TaskChannelInstance with HTTP info - :returns: Page of TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskChannelInstance with HTTP info - return TaskChannelPage(self._version, response, self._solution) - def create(self, friendly_name, unique_name, - channel_optimized_routing=values.unset): + :returns: ApiResponse with instance, status code, and headers """ - Create the TaskChannelInstance + return await self._proxy.fetch_with_http_info_async() - :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 + def update( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> "TaskChannelInstance": + """ + Update the TaskChannelInstance - :returns: The created TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The updated TaskChannelInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'UniqueName': unique_name, - 'ChannelOptimizedRouting': channel_optimized_routing, - }) + return self._proxy.update( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> "TaskChannelInstance": + """ + Asynchronous coroutine to update the TaskChannelInstance - return TaskChannelInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. - def get(self, sid): + :returns: The updated TaskChannelInstance """ - Constructs a TaskChannelContext + return await self._proxy.update_async( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the TaskChannelInstance with HTTP info - :param sid: The SID of the TaskChannel resource to fetch + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext + :returns: ApiResponse with instance, status code, and headers """ - return TaskChannelContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - Constructs a TaskChannelContext + Asynchronous coroutine to update the TaskChannelInstance with HTTP info - :param sid: The SID of the TaskChannel resource to fetch + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext + :returns: ApiResponse with instance, status code, and headers """ - return TaskChannelContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) - 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 TaskChannelPage(Page): - """ """ +class TaskChannelContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ - Initialize the TaskChannelPage - - :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 + Initialize the TaskChannelContext - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelPage - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelPage + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Task Channel to update. + :param sid: The SID of the Task Channel resource to update. """ - super(TaskChannelPage, 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}/TaskChannels/{sid}".format( + **self._solution + ) - def get_instance(self, payload): + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of TaskChannelInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return TaskChannelInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + Deletes the TaskChannelInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the TaskChannelInstance and return response metadata -class TaskChannelContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, workspace_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the TaskChannelContext + Internal async helper for delete operation - :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: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext + async def delete_async(self) -> bool: """ - super(TaskChannelContext, self).__init__(version) + Asynchronous coroutine that deletes the TaskChannelInstance - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/TaskChannels/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TaskChannelInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TaskChannelInstance: """ Fetch the TaskChannelInstance + :returns: The fetched TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TaskChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TaskChannelInstance: + """ + Asynchronous coroutine to fetch the TaskChannelInstance + + + :returns: The fetched TaskChannelInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._update( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) + return TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the TaskChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) + instance = TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Asynchronous coroutine to update the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The updated TaskChannelInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) 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_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - Deletes the TaskChannelInstance + Asynchronous coroutine to update the TaskChannelInstance and return response metadata - :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) + instance = TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 + + :param payload: Payload response from the API + """ + + return TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance + :returns: Machine friendly representation """ - super(TaskChannelInstance, 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')), - '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'), +class TaskChannelList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the TaskChannelList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Task Channel to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, } + self._uri = "/Workspaces/{workspace_sid}/TaskChannels".format(**self._solution) - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: TaskChannelContext for this TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: """ - if self._context is None: - self._context = TaskChannelContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the TaskChannelInstance - @property - def account_sid(self): + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. + :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The created TaskChannelInstance """ - :returns: The SID of the Account that created the resource - :rtype: unicode + payload, _, _ = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + channel_optimized_routing=channel_optimized_routing, + ) + return TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def create_with_http_info( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['account_sid'] + Create the TaskChannelInstance and return response metadata - @property - def date_created(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: ApiResponse with instance, status code, and headers """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + payload, status_code, headers = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + channel_optimized_routing=channel_optimized_routing, + ) + instance = TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> tuple: """ - return self._properties['date_created'] + Internal async helper for create operation - @property - def date_updated(self): + Returns: + tuple: (payload, status_code, headers) """ - :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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + channel_optimized_routing=channel_optimized_routing, + ) + return TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_with_http_info_async( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['friendly_name'] + Asynchronously create the TaskChannelInstance and return response metadata - @property - def sid(self): + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. + :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The unique string that identifies the resource - :rtype: unicode + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + channel_optimized_routing=channel_optimized_routing, + ) + instance = TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TaskChannelInstance]: """ - return self._properties['sid'] + 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 = self.page(page_size=limits["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['unique_name'] + 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 workspace_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 Workspace that contains 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['workspace_sid'] + Streams TaskChannelInstance and returns headers from first page - @property - def channel_optimized_routing(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: Whether the TaskChannel will prioritize Workers that have been idle - :rtype: bool + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['channel_optimized_routing'] + Asynchronously streams TaskChannelInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskChannelInstance]: """ - :returns: The absolute URL of the TaskChannel resource - :rtype: unicode + Lists TaskChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['url'] - @property - def links(self): + return 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]: """ - :returns: The URLs of related resources - :rtype: unicode + Asynchronously lists TaskChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['links'] - def fetch(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Fetch the TaskChannelInstance + Lists TaskChannelInstance and returns headers from first page - :returns: The fetched TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._proxy.fetch() + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - def update(self, friendly_name=values.unset, - channel_optimized_routing=values.unset): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Update the TaskChannelInstance + Asynchronously lists TaskChannelInstance and returns headers from first page - :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 - :returns: The updated TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._proxy.update( - friendly_name=friendly_name, - channel_optimized_routing=channel_optimized_routing, + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - 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, + ) -> TaskChannelPage: """ - Deletes the TaskChannelInstance + Retrieve a single page of TaskChannelInstance 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 TaskChannelInstance """ - 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 TaskChannelPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskChannelPage: + """ + Asynchronously retrieve a single page of TaskChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TaskChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TaskChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TaskChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TaskChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> TaskChannelPage: + """ + Retrieve a specific page of TaskChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TaskChannelPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> TaskChannelPage: + """ + Asynchronously retrieve a specific page of TaskChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TaskChannelPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> TaskChannelContext: + """ + Constructs a TaskChannelContext + + :param sid: The SID of the Task Channel resource to update. + """ + return TaskChannelContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> TaskChannelContext: + """ + Constructs a TaskChannelContext + + :param sid: The SID of the Task Channel resource to update. + """ + return TaskChannelContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 b1d8b9fd2c..02213bbcc8 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py @@ -1,619 +1,708 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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 +class TaskQueueInstance(InstanceResource): - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace that contains the TaskQueue + class TaskOrder(object): + FIFO = "FIFO" + LIFO = "LIFO" - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList - """ - super(TaskQueueList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/TaskQueues'.format(**self._solution) + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } - # Components - self._statistics = None + 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'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, friendly_name=values.unset, - evaluate_worker_attributes=values.unset, worker_sid=values.unset, - limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists TaskQueueInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the TaskQueueInstance - :param unicode friendly_name: The friendly_name 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 delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of TaskQueueInstance records from the API. - Request is executed immediately + Deletes the TaskQueueInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - data = values.of({ - 'FriendlyName': friendly_name, - 'EvaluateWorkerAttributes': evaluate_worker_attributes, - 'WorkerSid': worker_sid, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.delete_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TaskQueueInstance with HTTP info - return TaskQueuePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with success boolean, status code, and headers """ - Retrieve a specific page of TaskQueueInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + return await self._proxy.delete_with_http_info_async() - :returns: Page of TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueuePage + def fetch(self) -> "TaskQueueInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Fetch the TaskQueueInstance - 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): + :returns: The fetched TaskQueueInstance """ - Create 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 + return self._proxy.fetch() - :returns: The created TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance + async def fetch_async(self) -> "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, - }) + Asynchronous coroutine to fetch the TaskQueueInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return TaskQueueInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + :returns: The fetched TaskQueueInstance + """ + return await self._proxy.fetch_async() - @property - def statistics(self): + def fetch_with_http_info(self) -> ApiResponse: """ - Access the statistics + Fetch the TaskQueueInstance with HTTP info - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsList + + :returns: ApiResponse with instance, status code, and headers """ - if self._statistics is None: - self._statistics = TaskQueuesStatisticsList( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._statistics + return self._proxy.fetch_with_http_info() - def get(self, sid): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Constructs a TaskQueueContext + Asynchronous coroutine to fetch the TaskQueueInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return TaskQueueContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + return await self._proxy.fetch_with_http_info_async() - def __call__(self, sid): + def update( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> "TaskQueueInstance": """ - Constructs a TaskQueueContext + Update the TaskQueueInstance - :param sid: The SID of the resource to + :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: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueContext + :returns: The updated TaskQueueInstance """ - return TaskQueueContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=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, + ) - def __repr__(self): + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> "TaskQueueInstance": + """ + Asynchronous coroutine to update the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: The updated TaskQueueInstance """ - Provide a friendly representation + 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, + ) - :returns: Machine friendly representation - :rtype: str + def update_with_http_info( + 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, + ) -> ApiResponse: """ - return '' + Update the TaskQueueInstance with HTTP info + :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: -class TaskQueuePage(Page): - """ """ + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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, + ) - def __init__(self, version, response, solution): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Initialize the TaskQueuePage + Asynchronous coroutine to update the TaskQueueInstance with HTTP info - :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 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: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueuePage - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueuePage + :returns: ApiResponse with instance, status code, and headers """ - super(TaskQueuePage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return await self._proxy.update_with_http_info_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, + ) - def get_instance(self, payload): + @property + def cumulative_statistics(self) -> TaskQueueCumulativeStatisticsList: """ - Build an instance of TaskQueueInstance + Access the cumulative_statistics + """ + return self._proxy.cumulative_statistics - :param dict payload: Payload response from the API + @property + def real_time_statistics(self) -> TaskQueueRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + return self._proxy.real_time_statistics - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance + @property + def statistics(self) -> TaskQueueStatisticsList: """ - return TaskQueueInstance(self._version, payload, workspace_sid=self._solution['workspace_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 TaskQueueContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid, sid): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ Initialize the TaskQueueContext - :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 + :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(TaskQueueContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/TaskQueues/{sid}'.format(**self._solution) + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues/{sid}".format( + **self._solution + ) - # Dependents - self._statistics = None - self._real_time_statistics = None - self._cumulative_statistics = None + self._cumulative_statistics: Optional[TaskQueueCumulativeStatisticsList] = None + self._real_time_statistics: Optional[TaskQueueRealTimeStatisticsList] = None + self._statistics: Optional[TaskQueueStatisticsList] = None - def fetch(self): + def _delete(self) -> tuple: """ - Fetch the TaskQueueInstance + Internal helper for delete operation - :returns: The fetched TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return TaskQueueInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers ) - 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 delete(self) -> bool: """ - Update the TaskQueueInstance + Deletes 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 - :returns: The updated TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'TargetWorkers': target_workers, - 'ReservationActivitySid': reservation_activity_sid, - 'AssignmentActivitySid': assignment_activity_sid, - 'MaxReservedWorkers': max_reserved_workers, - 'TaskOrder': task_order, - }) + success, _, _ = self._delete() + return success - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TaskQueueInstance and return response metadata - return TaskQueueInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - def delete(self): + :returns: ApiResponse with success boolean, status code, and headers """ - Deletes the TaskQueueInstance + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def _delete_async(self) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal async helper for delete operation - @property - def statistics(self): + Returns: + tuple: (success_boolean, status_code, headers) """ - 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 - """ - if self._statistics is None: - self._statistics = TaskQueueStatisticsList( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['sid'], - ) - return self._statistics + headers = values.of({}) - @property - def real_time_statistics(self): + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - Access the real_time_statistics + Asynchronous coroutine that deletes the TaskQueueInstance + - :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 + :returns: True if delete succeeds, False otherwise """ - 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'], - ) - return self._real_time_statistics + success, _, _ = await self._delete_async() + return success - @property - def cumulative_statistics(self): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Access the cumulative_statistics + Asynchronous coroutine that deletes the TaskQueueInstance and return response metadata - :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 + + :returns: ApiResponse with success boolean, status code, and headers """ - if self._cumulative_statistics is None: - self._cumulative_statistics = TaskQueueCumulativeStatisticsList( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['sid'], - ) - return self._cumulative_statistics + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __repr__(self): + def _fetch(self) -> tuple: """ - Provide a friendly representation + Internal helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) -class TaskQueueInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - class TaskOrder(object): - FIFO = "FIFO" - LIFO = "LIFO" + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - 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'), - } + def fetch(self) -> TaskQueueInstance: + """ + Fetch the TaskQueueInstance - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): + :returns: The fetched TaskQueueInstance """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload, _, _ = self._fetch() + return TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - :returns: TaskQueueContext for this TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueContext + def fetch_with_http_info(self) -> ApiResponse: """ - if self._context is None: - self._context = TaskQueueContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - return self._context + Fetch the TaskQueueInstance and return response metadata - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - @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: ApiResponse with instance, status code, and headers """ - return self._properties['assignment_activity_sid'] + payload, status_code, headers = self._fetch() + instance = TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def assignment_activity_name(self): + async def _fetch_async(self) -> tuple: """ - :returns: The name of the Activity to assign Workers when a task is assigned for them - :rtype: unicode - """ - return self._properties['assignment_activity_name'] + Internal async helper for fetch operation - @property - def date_created(self): + Returns: + tuple: (payload, status_code, headers) """ - :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'] + headers = values.of({}) - @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 max_reserved_workers(self): - """ - :returns: The maximum number of Workers to reserve - :rtype: unicode - """ - return self._properties['max_reserved_workers'] + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - @property - def reservation_activity_sid(self): + async def fetch_async(self) -> TaskQueueInstance: """ - :returns: The SID of the Activity to assign Workers once a task is reserved for them - :rtype: unicode - """ - return self._properties['reservation_activity_sid'] + Asynchronous coroutine to fetch 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'] - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: The fetched TaskQueueInstance """ - return self._properties['sid'] + payload, _, _ = await self._fetch_async() + return TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - @property - def target_workers(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue - :rtype: unicode - """ - return self._properties['target_workers'] + Asynchronous coroutine to fetch the TaskQueueInstance and return response metadata - @property - def task_order(self): - """ - :returns: How Tasks will be assigned to Workers - :rtype: TaskQueueInstance.TaskOrder - """ - return self._properties['task_order'] - @property - def url(self): - """ - :returns: The absolute URL of the TaskQueue resource - :rtype: unicode + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['url'] + payload, status_code, headers = await self._fetch_async() + instance = TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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({}) - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace that contains the TaskQueue - :rtype: unicode - """ - return self._properties['workspace_sid'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def links(self): - """ - :returns: The URLs of related resources - :rtype: unicode - """ - return self._properties['links'] + headers["Accept"] = "application/json" - def fetch(self): + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - Fetch the TaskQueueInstance + Update the TaskQueueInstance - :returns: The fetched TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: The updated TaskQueueInstance """ - return self._proxy.fetch() + payload, _, _ = self._update( + friendly_name=friendly_name, + target_workers=target_workers, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + ) + return TaskQueueInstance( + self._version, + payload, + 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_with_http_info( + 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, + ) -> ApiResponse: """ - Update the TaskQueueInstance + Update the TaskQueueInstance and return response metadata + + :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: - :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 + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> TaskQueueInstance: + """ + Asynchronous coroutine to update the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: :returns: The updated TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance """ - return self._proxy.update( + payload, _, _ = await self._update_async( friendly_name=friendly_name, target_workers=target_workers, reservation_activity_sid=reservation_activity_sid, @@ -621,52 +710,911 @@ def update(self, friendly_name=values.unset, target_workers=values.unset, max_reserved_workers=max_reserved_workers, task_order=task_order, ) + return TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - def delete(self): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Deletes the TaskQueueInstance + Asynchronous coroutine to update the TaskQueueInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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: ApiResponse with instance, status code, and headers """ - return self._proxy.delete() + payload, status_code, headers = await self._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, + ) + instance = TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 """ - return self._proxy.statistics + if self._cumulative_statistics is None: + self._cumulative_statistics = TaskQueueCumulativeStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._cumulative_statistics @property - def real_time_statistics(self): + def real_time_statistics(self) -> TaskQueueRealTimeStatisticsList: """ Access the real_time_statistics + """ + if self._real_time_statistics is None: + self._real_time_statistics = TaskQueueRealTimeStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._real_time_statistics + + @property + def statistics(self) -> TaskQueueStatisticsList: + """ + Access the statistics + """ + if self._statistics is None: + self._statistics = TaskQueueStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._statistics - :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 + def __repr__(self) -> str: """ - return self._proxy.real_time_statistics + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TaskQueuePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TaskQueueInstance: + """ + Build an instance of TaskQueueInstance + + :param payload: Payload response from the API + """ + + return TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TaskQueueList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the TaskQueueList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues".format(**self._solution) + + self._bulk_real_time_statistics: Optional[ + TaskQueueBulkRealTimeStatisticsList + ] = None + self._statistics: Optional[TaskQueuesStatisticsList] = None + + def _create( + self, + friendly_name: str, + target_workers: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + target_workers: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + ) -> TaskQueueInstance: + """ + Create the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). + :param max_reserved_workers: The maximum number of Workers to reserve for the assignment of a Task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. + :param task_order: + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. + + :returns: The created TaskQueueInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + target_workers=target_workers, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + ) + return TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the TaskQueueInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + target_workers=target_workers, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + ) + instance = TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + target_workers=target_workers, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + ) + return TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the TaskQueueInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + target_workers=target_workers, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + ) + instance = TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TaskQueueInstance]: + """ + Streams TaskQueueInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TaskQueueInstance]: + """ + Asynchronously streams TaskQueueInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams TaskQueueInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams TaskQueueInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskQueueInstance]: + """ + Lists TaskQueueInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskQueueInstance]: + """ + Asynchronously lists TaskQueueInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists TaskQueueInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists TaskQueueInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskQueuePage: + """ + Retrieve a single page of TaskQueueInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param ordering: Sorting parameter for TaskQueues + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskQueueInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "EvaluateWorkerAttributes": evaluate_worker_attributes, + "WorkerSid": worker_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskQueuePage(self._version, response, solution=self._solution) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskQueuePage: + """ + Asynchronously retrieve a single page of TaskQueueInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param ordering: Sorting parameter for TaskQueues + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskQueueInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "EvaluateWorkerAttributes": evaluate_worker_attributes, + "WorkerSid": worker_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskQueuePage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with TaskQueuePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TaskQueuePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with TaskQueuePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TaskQueuePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> TaskQueuePage: + """ + Retrieve a specific page of TaskQueueInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskQueueInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TaskQueuePage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> TaskQueuePage: + """ + Asynchronously retrieve a specific page of TaskQueueInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskQueueInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TaskQueuePage(self._version, response, solution=self._solution) @property - def cumulative_statistics(self): + def bulk_real_time_statistics(self) -> TaskQueueBulkRealTimeStatisticsList: """ - Access the cumulative_statistics + Access the bulk_real_time_statistics + """ + if self._bulk_real_time_statistics is None: + self._bulk_real_time_statistics = TaskQueueBulkRealTimeStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._bulk_real_time_statistics - :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 + @property + def statistics(self) -> TaskQueuesStatisticsList: """ - return self._proxy.cumulative_statistics + Access the statistics + """ + if self._statistics is None: + self._statistics = TaskQueuesStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._statistics + + def get(self, sid: str) -> TaskQueueContext: + """ + Constructs a TaskQueueContext + + :param sid: The SID of the TaskQueue resource to update. + """ + return TaskQueueContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> TaskQueueContext: + """ + Constructs a TaskQueueContext + + :param sid: The SID of the TaskQueue resource to update. + """ + return TaskQueueContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..5273d75dea --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py @@ -0,0 +1,190 @@ +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.api_response import ApiResponse + +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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, body: Union[object, object] = values.unset + ) -> TaskQueueBulkRealTimeStatisticsInstance: + """ + Create the TaskQueueBulkRealTimeStatisticsInstance + + :param body: + + :returns: The created TaskQueueBulkRealTimeStatisticsInstance + """ + payload, _, _ = self._create(body=body) + return TaskQueueBulkRealTimeStatisticsInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def create_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the TaskQueueBulkRealTimeStatisticsInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body) + instance = TaskQueueBulkRealTimeStatisticsInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> TaskQueueBulkRealTimeStatisticsInstance: + """ + Asynchronously create the TaskQueueBulkRealTimeStatisticsInstance + + :param body: + + :returns: The created TaskQueueBulkRealTimeStatisticsInstance + """ + payload, _, _ = await self._create_async(body=body) + return TaskQueueBulkRealTimeStatisticsInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the TaskQueueBulkRealTimeStatisticsInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(body=body) + instance = TaskQueueBulkRealTimeStatisticsInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..5741772450 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,542 @@ -# 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.api_response import ApiResponse 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 TaskQueueCumulativeStatisticsList(ListResource): - """ """ +class TaskQueueCumulativeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + :ivar avg_task_acceptance_time: The average time in seconds between Task creation and acceptance. + :ivar start_time: The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar end_time: The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar reservations_created: The total number of Reservations created for Tasks in the TaskQueue. + :ivar reservations_accepted: The total number of Reservations accepted for Tasks in the TaskQueue. + :ivar reservations_rejected: The total number of Reservations rejected for Tasks in the TaskQueue. + :ivar reservations_timed_out: The total number of Reservations that timed out for Tasks in the TaskQueue. + :ivar reservations_canceled: The total number of Reservations canceled for Tasks in the TaskQueue. + :ivar reservations_rescinded: The total number of Reservations rescinded. + :ivar split_by_wait_time: A list of objects that describe the number of Tasks canceled and reservations accepted above and below the thresholds specified in seconds. + :ivar task_queue_sid: The SID of the TaskQueue from which these statistics were calculated. + :ivar wait_duration_until_accepted: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks accepted while in the TaskQueue. Calculation is based on the time when the Tasks were created. For transfers, the wait duration is counted from the moment ***the Task was created***, and not from when the transfer was initiated. + :ivar wait_duration_until_canceled: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks canceled while in the TaskQueue. + :ivar wait_duration_in_queue_until_accepted: The relative wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks accepted while in the TaskQueue. Calculation is based on the time when the Tasks entered the TaskQueue. + :ivar tasks_canceled: The total number of Tasks canceled in the TaskQueue. + :ivar tasks_completed: The total number of Tasks completed in the TaskQueue. + :ivar tasks_deleted: The total number of Tasks deleted in the TaskQueue. + :ivar tasks_entered: The total number of Tasks entered into the TaskQueue. + :ivar tasks_moved: The total number of Tasks that were moved from one queue to another. + :ivar workspace_sid: The SID of the Workspace that contains the TaskQueue. + :ivar url: The absolute URL of the TaskQueue statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + task_queue_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.avg_task_acceptance_time: Optional[int] = deserialize.integer( + payload.get("avg_task_acceptance_time") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.reservations_created: Optional[int] = deserialize.integer( + payload.get("reservations_created") + ) + self.reservations_accepted: Optional[int] = deserialize.integer( + payload.get("reservations_accepted") + ) + self.reservations_rejected: Optional[int] = deserialize.integer( + payload.get("reservations_rejected") + ) + self.reservations_timed_out: Optional[int] = deserialize.integer( + payload.get("reservations_timed_out") + ) + self.reservations_canceled: Optional[int] = deserialize.integer( + payload.get("reservations_canceled") + ) + self.reservations_rescinded: Optional[int] = deserialize.integer( + payload.get("reservations_rescinded") + ) + self.split_by_wait_time: Optional[Dict[str, object]] = payload.get( + "split_by_wait_time" + ) + self.task_queue_sid: Optional[str] = payload.get("task_queue_sid") + self.wait_duration_until_accepted: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_accepted" + ) + self.wait_duration_until_canceled: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_canceled" + ) + self.wait_duration_in_queue_until_accepted: Optional[Dict[str, object]] = ( + payload.get("wait_duration_in_queue_until_accepted") + ) + self.tasks_canceled: Optional[int] = deserialize.integer( + payload.get("tasks_canceled") + ) + self.tasks_completed: Optional[int] = deserialize.integer( + payload.get("tasks_completed") + ) + self.tasks_deleted: Optional[int] = deserialize.integer( + payload.get("tasks_deleted") + ) + self.tasks_entered: Optional[int] = deserialize.integer( + payload.get("tasks_entered") + ) + self.tasks_moved: Optional[int] = deserialize.integer( + payload.get("tasks_moved") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") - def __init__(self, version, workspace_sid, task_queue_sid): - """ - Initialize the TaskQueueCumulativeStatisticsList + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } - :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 + self._context: Optional[TaskQueueCumulativeStatisticsContext] = None - :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 + @property + def _proxy(self) -> "TaskQueueCumulativeStatisticsContext": """ - super(TaskQueueCumulativeStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'task_queue_sid': task_queue_sid, } + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def get(self): + :returns: TaskQueueCumulativeStatisticsContext for this TaskQueueCumulativeStatisticsInstance """ - Constructs a 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 - :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 + 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": """ - return TaskQueueCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], - ) + Fetch the TaskQueueCumulativeStatisticsInstance - def __call__(self): - """ - Constructs a TaskQueueCumulativeStatisticsContext + :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.TaskQueueCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsContext + :returns: The fetched TaskQueueCumulativeStatisticsInstance """ - return TaskQueueCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, ) - def __repr__(self): + 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": """ - Provide a friendly representation + Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance - :returns: Machine friendly representation - :rtype: str - """ - return '' + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + :returns: The fetched TaskQueueCumulativeStatisticsInstance + """ + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) -class TaskQueueCumulativeStatisticsPage(Page): - """ """ - - def __init__(self, version, response, solution): + def fetch_with_http_info( + 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, + ) -> ApiResponse: """ - Initialize the TaskQueueCumulativeStatisticsPage + Fetch the TaskQueueCumulativeStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - super(TaskQueueCumulativeStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: """ - Build an instance of TaskQueueCumulativeStatisticsInstance + Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return TaskQueueCumulativeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], + return await self._proxy.fetch_with_http_info_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: 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, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) - def fetch(self, end_date=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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, ) - + payload, _, _ = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return TaskQueueCumulativeStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class TaskQueueCumulativeStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid, task_queue_sid): - """ - Initialize the TaskQueueCumulativeStatisticsInstance - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsInstance - """ - super(TaskQueueCumulativeStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.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 - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def fetch_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['account_sid'] + Fetch the TaskQueueCumulativeStatisticsInstance and return response metadata - @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'] + :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 start_time(self): + :returns: ApiResponse with instance, status code, and headers """ - :returns: The beginning of the interval during which these statistics were calculated - :rtype: datetime - """ - return self._properties['start_time'] + payload, status_code, headers = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = TaskQueueCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) - @property - def end_time(self): - """ - :returns: The end of the interval during which these statistics were calculated - :rtype: datetime - """ - return self._properties['end_time'] + headers = values.of({}) - @property - def reservations_created(self): - """ - :returns: The total number of Reservations created for Tasks in the TaskQueue - :rtype: unicode - """ - return self._properties['reservations_created'] + headers["Accept"] = "application/json" - @property - def reservations_accepted(self): - """ - :returns: The total number of Reservations accepted for Tasks in the TaskQueue - :rtype: unicode - """ - return self._properties['reservations_accepted'] + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - @property - def reservations_rejected(self): - """ - :returns: The total number of Reservations rejected for Tasks in the TaskQueue - :rtype: unicode + 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: """ - return self._properties['reservations_rejected'] + Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance - @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'] + :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_canceled(self): - """ - :returns: The total number of Reservations canceled for Tasks in the TaskQueue - :rtype: unicode + :returns: The fetched TaskQueueCumulativeStatisticsInstance """ - return self._properties['reservations_canceled'] + payload, _, _ = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + return TaskQueueCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - @property - def reservations_rescinded(self): + async def fetch_with_http_info_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, + ) -> ApiResponse: """ - :returns: The total number of Reservations rescinded - :rtype: unicode - """ - return self._properties['reservations_rescinded'] + Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance and return response metadata - @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'] + :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 task_queue_sid(self): + :returns: ApiResponse with instance, status code, and headers """ - :returns: The SID of the TaskQueue from which these statistics were calculated - :rtype: unicode - """ - return self._properties['task_queue_sid'] + payload, status_code, headers = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = TaskQueueCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @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): + def get(self) -> TaskQueueCumulativeStatisticsContext: """ - :returns: The SID of the Workspace that contains the TaskQueue - :rtype: unicode - """ - 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..94dc68cbbc 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,379 @@ -# 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.api_response import ApiResponse 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 TaskQueueRealTimeStatisticsList(ListResource): - """ """ +class TaskQueueRealTimeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + :ivar activity_statistics: The number of current Workers by Activity. + :ivar longest_task_waiting_age: The age of the longest waiting Task. + :ivar longest_task_waiting_sid: The SID of the longest waiting Task. + :ivar longest_relative_task_age_in_queue: The relative age in the TaskQueue for the longest waiting Task. Calculation is based on the time when the Task entered the TaskQueue. + :ivar longest_relative_task_sid_in_queue: The Task SID of the Task waiting in the TaskQueue the longest. Calculation is based on the time when the Task entered the TaskQueue. + :ivar task_queue_sid: The SID of the TaskQueue from which these statistics were calculated. + :ivar tasks_by_priority: The number of Tasks by priority. For example: `{\"0\": \"10\", \"99\": \"5\"}` shows 10 Tasks at priority 0 and 5 at priority 99. + :ivar tasks_by_status: The number of Tasks by their current status. For example: `{\"pending\": \"1\", \"reserved\": \"3\", \"assigned\": \"2\", \"completed\": \"5\"}`. + :ivar total_available_workers: The total number of Workers in the TaskQueue with an `available` status. Workers with an `available` status may already have active interactions or may have none. + :ivar total_eligible_workers: The total number of Workers eligible for Tasks in the TaskQueue, independent of their Activity state. + :ivar total_tasks: The total number of Tasks. + :ivar workspace_sid: The SID of the Workspace that contains the TaskQueue. + :ivar url: The absolute URL of the TaskQueue statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + task_queue_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.activity_statistics: Optional[List[Dict[str, object]]] = payload.get( + "activity_statistics" + ) + self.longest_task_waiting_age: Optional[int] = deserialize.integer( + payload.get("longest_task_waiting_age") + ) + self.longest_task_waiting_sid: Optional[str] = payload.get( + "longest_task_waiting_sid" + ) + self.longest_relative_task_age_in_queue: Optional[int] = deserialize.integer( + payload.get("longest_relative_task_age_in_queue") + ) + self.longest_relative_task_sid_in_queue: Optional[str] = payload.get( + "longest_relative_task_sid_in_queue" + ) + self.task_queue_sid: Optional[str] = payload.get("task_queue_sid") + self.tasks_by_priority: Optional[Dict[str, object]] = payload.get( + "tasks_by_priority" + ) + self.tasks_by_status: Optional[Dict[str, object]] = payload.get( + "tasks_by_status" + ) + self.total_available_workers: Optional[int] = deserialize.integer( + payload.get("total_available_workers") + ) + self.total_eligible_workers: Optional[int] = deserialize.integer( + payload.get("total_eligible_workers") + ) + self.total_tasks: Optional[int] = deserialize.integer( + payload.get("total_tasks") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") - def __init__(self, version, workspace_sid, task_queue_sid): - """ - Initialize the TaskQueueRealTimeStatisticsList + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } - :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 + self._context: Optional[TaskQueueRealTimeStatisticsContext] = None - :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 + @property + def _proxy(self) -> "TaskQueueRealTimeStatisticsContext": """ - super(TaskQueueRealTimeStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'task_queue_sid': task_queue_sid, } + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def get(self): + :returns: TaskQueueRealTimeStatisticsContext for this TaskQueueRealTimeStatisticsInstance """ - Constructs a 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 - :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 + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "TaskQueueRealTimeStatisticsInstance": """ - return TaskQueueRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], - ) + Fetch the TaskQueueRealTimeStatisticsInstance - def __call__(self): - """ - Constructs a TaskQueueRealTimeStatisticsContext + :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.TaskQueueRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsContext + :returns: The fetched TaskQueueRealTimeStatisticsInstance """ - return TaskQueueRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], + return self._proxy.fetch( + task_channel=task_channel, ) - def __repr__(self): + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> "TaskQueueRealTimeStatisticsInstance": """ - Provide a friendly representation + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance - :returns: Machine friendly representation - :rtype: str - """ - return '' + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :returns: The fetched TaskQueueRealTimeStatisticsInstance + """ + return await self._proxy.fetch_async( + task_channel=task_channel, + ) -class TaskQueueRealTimeStatisticsPage(Page): - """ """ - - def __init__(self, version, response, solution): + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: """ - Initialize the TaskQueueRealTimeStatisticsPage + Fetch the TaskQueueRealTimeStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - super(TaskQueueRealTimeStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info( + task_channel=task_channel, + ) - def get_instance(self, payload): + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: """ - Build an instance of TaskQueueRealTimeStatisticsInstance + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return TaskQueueRealTimeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], + return await self._proxy.fetch_with_http_info_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: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation - def fetch(self, task_channel=values.unset): + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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._fetch(task_channel=task_channel) + return TaskQueueRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the TaskQueueRealTimeStatisticsInstance and return response metadata - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + :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`. - return TaskQueueRealTimeStatisticsInstance( + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(task_channel=task_channel) + instance = TaskQueueRealTimeStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + params = values.of( + { + "TaskChannel": task_channel, + } + ) -class TaskQueueRealTimeStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid, task_queue_sid): - """ - Initialize the TaskQueueRealTimeStatisticsInstance - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance - """ - super(TaskQueueRealTimeStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.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'), - } + headers = values.of({}) - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'task_queue_sid': task_queue_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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - :returns: TaskQueueRealTimeStatisticsContext for this TaskQueueRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsContext + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> 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 + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_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 activity_statistics(self): - """ - :returns: The number of current Workers by Activity - :rtype: dict + :returns: The fetched TaskQueueRealTimeStatisticsInstance """ - return self._properties['activity_statistics'] + payload, _, _ = await self._fetch_async(task_channel=task_channel) + return TaskQueueRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - @property - def longest_task_waiting_age(self): + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: """ - :returns: The age of the longest waiting Task - :rtype: unicode - """ - return self._properties['longest_task_waiting_age'] + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance and return response metadata - @property - def longest_task_waiting_sid(self): - """ - :returns: The SID of the longest waiting Task - :rtype: unicode - """ - return self._properties['longest_task_waiting_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 longest_relative_task_age_in_queue(self): - """ - :returns: The relative age in the TaskQueue for the longest waiting Task. - :rtype: unicode + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['longest_relative_task_age_in_queue'] + payload, status_code, headers = await self._fetch_async( + task_channel=task_channel + ) + instance = TaskQueueRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def longest_relative_task_sid_in_queue(self): + def __repr__(self) -> str: """ - :returns: The SID of the Task waiting in the TaskQueue the longest. - :rtype: unicode - """ - return self._properties['longest_relative_task_sid_in_queue'] + Provide a friendly representation - @property - def task_queue_sid(self): - """ - :returns: The SID of the TaskQueue from which these statistics were calculated - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['task_queue_sid'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - @property - def tasks_by_priority(self): - """ - :returns: The number of Tasks by priority - :rtype: dict - """ - return self._properties['tasks_by_priority'] - @property - def tasks_by_status(self): - """ - :returns: The number of Tasks by their current status - :rtype: dict - """ - return self._properties['tasks_by_status'] +class TaskQueueRealTimeStatisticsList(ListResource): - @property - def total_available_workers(self): - """ - :returns: The total number of Workers available for Tasks in the TaskQueue - :rtype: unicode + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ - return self._properties['total_available_workers'] + Initialize the TaskQueueRealTimeStatisticsList - @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'] + :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_tasks(self): - """ - :returns: The total number of Tasks - :rtype: unicode """ - return self._properties['total_tasks'] + super().__init__(version) - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace that contains the TaskQueue - :rtype: unicode - """ - return self._properties['workspace_sid'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } - @property - def url(self): - """ - :returns: The absolute URL of the TaskQueue statistics resource - :rtype: unicode + def get(self) -> TaskQueueRealTimeStatisticsContext: """ - return self._properties['url'] + Constructs a TaskQueueRealTimeStatisticsContext - def fetch(self, task_channel=values.unset): """ - Fetch the TaskQueueRealTimeStatisticsInstance + return TaskQueueRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - :param unicode task_channel: The TaskChannel for which to fetch statistics + def __call__(self) -> TaskQueueRealTimeStatisticsContext: + """ + 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..444f3925a7 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,472 @@ -# 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.api_response import ApiResponse 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): - """ """ - def __init__(self, version, workspace_sid, task_queue_sid): - """ - Initialize the TaskQueueStatisticsList +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, + } - :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 + self._context: Optional[TaskQueueStatisticsContext] = None - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsList + @property + def _proxy(self) -> "TaskQueueStatisticsContext": """ - super(TaskQueueStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'task_queue_sid': task_queue_sid, } + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def get(self): + :returns: TaskQueueStatisticsContext for this TaskQueueStatisticsInstance """ - Constructs a TaskQueueStatisticsContext + if self._context is None: + self._context = TaskQueueStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return self._context - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "TaskQueueStatisticsInstance": """ - return TaskQueueStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], - ) + Fetch the TaskQueueStatisticsInstance - def __call__(self): - """ - Constructs a TaskQueueStatisticsContext + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext + :returns: The fetched TaskQueueStatisticsInstance """ - return TaskQueueStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + 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": """ - return '' + 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. -class TaskQueueStatisticsPage(Page): - """ """ + :returns: The fetched TaskQueueStatisticsInstance + """ + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) - def __init__(self, version, response, solution): + def fetch_with_http_info( + 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, + ) -> ApiResponse: """ - Initialize the TaskQueueStatisticsPage + Fetch the TaskQueueStatisticsInstance with HTTP info - :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 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.TaskQueueStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsPage + :returns: ApiResponse with instance, status code, and headers """ - super(TaskQueueStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: """ - Build an instance of TaskQueueStatisticsInstance + Asynchronous coroutine to fetch the TaskQueueStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return TaskQueueStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], + return await self._proxy.fetch_with_http_info_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class TaskQueueStatisticsContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid, task_queue_sid): + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ Initialize the TaskQueueStatisticsContext - :param Version version: Version that contains the resource - :param workspace_sid: The 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_statistics.TaskQueueStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to fetch. + :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics. """ - super(TaskQueueStatisticsContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'task_queue_sid': task_queue_sid, } - self._uri = '/Workspaces/{workspace_sid}/TaskQueues/{task_queue_sid}/Statistics'.format(**self._solution) + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/TaskQueues/{task_queue_sid}/Statistics".format( + **self._solution + ) + ) + + def _fetch( + self, + end_date: 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, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) - def fetch(self, end_date=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> TaskQueueStatisticsInstance: """ Fetch the TaskQueueStatisticsInstance - :param 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 + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. :returns: The fetched TaskQueueStatisticsInstance - :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, - }) - - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) - + payload, _, _ = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) 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 fetch_with_http_info( + 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, + ) -> ApiResponse: """ - Provide a friendly representation + Fetch the TaskQueueStatisticsInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + :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: ApiResponse with instance, status code, and headers """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + payload, status_code, headers = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = TaskQueueStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + headers = values.of({}) -class TaskQueueStatisticsInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, payload, workspace_sid, task_queue_sid): - """ - Initialize the TaskQueueStatisticsInstance + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsInstance + 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: """ - super(TaskQueueStatisticsInstance, self).__init__(version) + Asynchronous coroutine to fetch the TaskQueueStatisticsInstance - # 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'), - } + :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. - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'task_queue_sid': task_queue_sid, } - - @property - def _proxy(self): + :returns: The fetched TaskQueueStatisticsInstance """ - 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._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + return TaskQueueStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - :returns: TaskQueueStatisticsContext for this TaskQueueStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext + async def fetch_with_http_info_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, + ) -> ApiResponse: """ - 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 + Asynchronous coroutine to fetch the TaskQueueStatisticsInstance and return response metadata - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate 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. - @property - def cumulative(self): - """ - :returns: An object that contains the cumulative statistics for the TaskQueue - :rtype: dict + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['cumulative'] + payload, status_code, headers = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = TaskQueueStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def realtime(self): - """ - :returns: An object that contains the real-time statistics for the TaskQueue - :rtype: dict + def __repr__(self) -> str: """ - return self._properties['realtime'] + Provide a friendly representation - @property - def task_queue_sid(self): - """ - :returns: The SID of the TaskQueue from which these statistics were calculated - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['task_queue_sid'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace that contains the TaskQueue - :rtype: unicode + +class TaskQueueStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ - return self._properties['workspace_sid'] + Initialize the TaskQueueStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to fetch. + :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics. - @property - def url(self): """ - :returns: The absolute URL of the TaskQueue statistics resource - :rtype: unicode + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + + def get(self) -> TaskQueueStatisticsContext: """ - return self._properties['url'] + Constructs a TaskQueueStatisticsContext - def fetch(self, end_date=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): """ - Fetch the TaskQueueStatisticsInstance + return TaskQueueStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - :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 + def __call__(self) -> TaskQueueStatisticsContext: + """ + 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 7932f2e230..aa6fb95b0f 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,135 @@ -# 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.api_response import ApiResponse + from twilio.base.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 +137,569 @@ def stream(self, end_date=values.unset, friendly_name=values.unset, start_date=start_date, task_channel=task_channel, split_by_wait_time=split_by_wait_time, - page_size=limits['page_size'], + page_size=limits["page_size"], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, end_date=values.unset, friendly_name=values.unset, - minutes=values.unset, start_date=values.unset, - task_channel=values.unset, split_by_wait_time=values.unset, limit=None, - page_size=None): - """ - Lists TaskQueuesStatisticsInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TaskQueuesStatisticsInstance]: + """ + Asynchronously streams TaskQueuesStatisticsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :param datetime end_date: 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, - )) + page_size=limits["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): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams TaskQueuesStatisticsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - Retrieve a single page of TaskQueuesStatisticsInstance records from the API. - Request is executed immediately + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + page_size=limits["page_size"], + ) - :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 + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams TaskQueuesStatisticsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + page_size=limits["page_size"], + ) - :returns: Page of TaskQueuesStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsPage + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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, - }) + Lists TaskQueuesStatisticsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + limit=limit, + page_size=page_size, + ) + ) - return TaskQueuesStatisticsPage(self._version, response, self._solution) + async def list_async( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskQueuesStatisticsInstance]: + """ + Asynchronously lists TaskQueuesStatisticsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - def get_page(self, target_url): + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists TaskQueuesStatisticsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists TaskQueuesStatisticsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 '' + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Accept"] = "application/json" -class TaskQueuesStatisticsPage(Page): - """ """ + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskQueuesStatisticsPage( + self._version, response, solution=self._solution + ) - def __init__(self, version, response, solution): - """ - Initialize the TaskQueuesStatisticsPage + 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 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 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.TaskQueuesStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsPage + :returns: Page of TaskQueuesStatisticsInstance """ - super(TaskQueuesStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + 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 get_instance(self, payload): - """ - Build an instance of TaskQueuesStatisticsInstance + 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.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsInstance - """ - return TaskQueuesStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskQueuesStatisticsPage( + self._version, response, solution=self._solution ) - def __repr__(self): - """ - Provide a friendly representation + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with TaskQueuesStatisticsPage, status code, and headers + """ + 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, + } + ) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Accept"] = "application/json" -class TaskQueuesStatisticsInstance(InstanceResource): - """ """ + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TaskQueuesStatisticsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with TaskQueuesStatisticsPage, status code, and headers + """ + 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 __init__(self, version, payload, workspace_sid): - """ - Initialize the TaskQueuesStatisticsInstance + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsInstance - """ - super(TaskQueuesStatisticsInstance, self).__init__(version) + headers["Accept"] = "application/json" - # 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, } + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TaskQueuesStatisticsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def account_sid(self): + def get_page(self, target_url: str) -> TaskQueuesStatisticsPage: """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + Retrieve a specific page of TaskQueuesStatisticsInstance records from the API. + Request is executed immediately - @property - def cumulative(self): - """ - :returns: An object that contains the cumulative statistics for the TaskQueues - :rtype: dict - """ - return self._properties['cumulative'] + :param target_url: API-generated URL for the requested results page - @property - def realtime(self): - """ - :returns: An object that contains the real-time statistics for the TaskQueues - :rtype: dict + :returns: Page of TaskQueuesStatisticsInstance """ - return self._properties['realtime'] + response = self._version.domain.twilio.request("GET", target_url) + return TaskQueuesStatisticsPage( + self._version, response, solution=self._solution + ) - @property - def task_queue_sid(self): + async def get_page_async(self, target_url: str) -> TaskQueuesStatisticsPage: """ - :returns: The SID of the TaskQueue from which these statistics were calculated - :rtype: unicode - """ - return self._properties['task_queue_sid'] + Asynchronously retrieve a specific page of TaskQueuesStatisticsInstance records from the API. + Request is executed immediately - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace that contains the TaskQueues - :rtype: unicode + :param target_url: API-generated URL for the requested results page + + :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, solution=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 9d01f791b5..1295d3716e 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/__init__.py @@ -1,713 +1,1722 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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, + } - def __init__(self, version, workspace_sid): + self._context: Optional[WorkerContext] = None + + @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'], limits['page_limit']) - - def list(self, activity_name=values.unset, activity_sid=values.unset, - available=values.unset, friendly_name=values.unset, - target_workers_expression=values.unset, task_queue_name=values.unset, - task_queue_sid=values.unset, limit=None, page_size=None): + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: """ - Lists WorkerInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the WorkerInstance with HTTP info - :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) + :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: ApiResponse with success boolean, status code, and headers """ - 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.delete_with_http_info( + if_match=if_match, + ) - 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 delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: """ - Retrieve a single page of WorkerInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the WorkerInstance with HTTP info - :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 + :param if_match: The If-Match HTTP request header - :returns: Page of WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerPage + :returns: ApiResponse with success boolean, status code, and headers """ - 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, - }) + return await self._proxy.delete_with_http_info_async( + if_match=if_match, + ) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def fetch(self) -> "WorkerInstance": + """ + Fetch the WorkerInstance - return WorkerPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched WorkerInstance """ - Retrieve a specific page of WorkerInstance 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 WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerPage + async def fetch_async(self) -> "WorkerInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronous coroutine to fetch the WorkerInstance - return WorkerPage(self._version, response, self._solution) - def create(self, friendly_name, activity_sid=values.unset, - attributes=values.unset): + :returns: The fetched WorkerInstance """ - Create the WorkerInstance + return await self._proxy.fetch_async() - :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 - - :returns: The created WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance + def fetch_with_http_info(self) -> ApiResponse: """ - data = values.of({ - 'FriendlyName': friendly_name, - 'ActivitySid': activity_sid, - 'Attributes': attributes, - }) + Fetch the WorkerInstance with HTTP info - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return WorkerInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() - @property - def statistics(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Access the statistics + Asynchronous coroutine to fetch the WorkerInstance with HTTP info + - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsList + :returns: ApiResponse with instance, status code, and headers """ - if self._statistics is None: - self._statistics = WorkersStatisticsList( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._statistics + return await self._proxy.fetch_with_http_info_async() - def get(self, sid): + def update( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> "WorkerInstance": """ - Constructs a WorkerContext + Update the WorkerInstance - :param sid: The SID of the resource to fetch + :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: twilio.rest.taskrouter.v1.workspace.worker.WorkerContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerContext + :returns: The updated WorkerInstance """ - return WorkerContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + return self._proxy.update( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) - def __call__(self, sid): + async def update_async( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> "WorkerInstance": """ - Constructs a WorkerContext - - :param sid: The SID of the resource to fetch + Asynchronous coroutine to update the WorkerInstance - :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerContext - """ - return WorkerContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + :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`. - def __repr__(self): + :returns: The updated WorkerInstance """ - Provide a friendly representation + 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, + ) - :returns: Machine friendly representation - :rtype: str + def update_with_http_info( + 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, + ) -> ApiResponse: """ - return '' + Update the WorkerInstance with HTTP info + :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`. -class WorkerPage(Page): - """ """ + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) - def __init__(self, version, response, solution): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Initialize the WorkerPage + Asynchronous coroutine to update the WorkerInstance with HTTP info - :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 + :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: twilio.rest.taskrouter.v1.workspace.worker.WorkerPage - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerPage + :returns: ApiResponse with instance, status code, and headers """ - super(WorkerPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return await self._proxy.update_with_http_info_async( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) - def get_instance(self, payload): + @property + def reservations(self) -> ReservationList: """ - Build an instance of WorkerInstance + Access the reservations + """ + return self._proxy.reservations - :param dict payload: Payload response from the API + @property + def worker_channels(self) -> WorkerChannelList: + """ + Access the worker_channels + """ + return self._proxy.worker_channels - :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance + @property + def statistics(self) -> WorkerStatisticsList: + """ + Access the statistics """ - return WorkerInstance(self._version, payload, workspace_sid=self._solution['workspace_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 WorkerContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid, sid): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ Initialize the WorkerContext - :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 + :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(WorkerContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/Workers/{sid}'.format(**self._solution) + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/{sid}".format(**self._solution) - # Dependents - self._real_time_statistics = None - self._cumulative_statistics = None - self._statistics = None - self._reservations = None - self._worker_channels = None + self._reservations: Optional[ReservationList] = None + self._worker_channels: Optional[WorkerChannelList] = None + self._statistics: Optional[WorkerStatisticsList] = None - def fetch(self): + def _delete(self, if_match: Union[str, object] = values.unset) -> tuple: """ - Fetch the WorkerInstance + Internal helper for delete operation - :returns: The fetched WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return WorkerInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + headers = values.of( + { + "If-Match": if_match, + } ) - def update(self, activity_sid=values.unset, attributes=values.unset, - friendly_name=values.unset, - reject_pending_reservations=values.unset): - """ - 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 - - :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, ) + headers = values.of({}) - return WorkerInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers ) - def delete(self): + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ Deletes the WorkerInstance + :param if_match: The If-Match HTTP request header + :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + success, _, _ = self._delete(if_match=if_match) + return success - @property - def real_time_statistics(self): + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: """ - Access the real_time_statistics + Deletes the WorkerInstance and return response metadata - :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 + :param if_match: The If-Match HTTP request header - @property - def cumulative_statistics(self): + :returns: ApiResponse with success boolean, status code, and headers """ - Access the cumulative_statistics + success, status_code, headers = self._delete(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, headers=headers) - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList + async def _delete_async(self, if_match: Union[str, object] = values.unset) -> tuple: """ - if self._cumulative_statistics is None: - self._cumulative_statistics = WorkersCumulativeStatisticsList( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._cumulative_statistics + Internal async helper for delete operation - @property - def statistics(self): + Returns: + tuple: (success_boolean, status_code, headers) """ - Access the statistics + headers = values.of( + { + "If-Match": if_match, + } + ) - :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 + headers = values.of({}) - @property - def reservations(self): + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: """ - Access the reservations + Asynchronous coroutine that deletes the WorkerInstance - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationList + :param if_match: The If-Match HTTP request header + + :returns: True if delete succeeds, False otherwise """ - if self._reservations is None: - self._reservations = ReservationList( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['sid'], - ) - return self._reservations + success, _, _ = await self._delete_async(if_match=if_match) + return success - @property - def worker_channels(self): + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: """ - Access the worker_channels + Asynchronous coroutine that deletes the WorkerInstance and return response metadata + + :param if_match: The If-Match HTTP request header - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelList + :returns: ApiResponse with success boolean, status code, and headers """ - if self._worker_channels is None: - self._worker_channels = WorkerChannelList( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['sid'], - ) - return self._worker_channels + success, status_code, headers = await self._delete_async(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __repr__(self): + def _fetch(self) -> tuple: """ - Provide a friendly representation + Internal helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) -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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - @property - def _proxy(self): + def fetch(self) -> WorkerInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Fetch the WorkerInstance - :returns: WorkerContext for this WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerContext - """ - if self._context is None: - self._context = WorkerContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - return self._context - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: The fetched WorkerInstance """ - return self._properties['account_sid'] + payload, _, _ = self._fetch() + return WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - @property - def activity_name(self): + def fetch_with_http_info(self) -> ApiResponse: """ - :returns: The friendly_name of the Worker's current Activity - :rtype: unicode - """ - return self._properties['activity_name'] + Fetch the WorkerInstance and return response metadata - @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 + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['attributes'] + payload, status_code, headers = self._fetch() + instance = WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def available(self): + async def _fetch_async(self) -> tuple: """ - :returns: Whether the Worker is available to perform tasks - :rtype: bool - """ - return self._properties['available'] + Internal async helper for fetch operation - @property - def date_created(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - @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'] + headers = values.of({}) - @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 friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - @property - def sid(self): + async def fetch_async(self) -> WorkerInstance: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Asynchronous coroutine to fetch the WorkerInstance - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace that contains the Worker - :rtype: unicode - """ - return self._properties['workspace_sid'] - @property - def url(self): - """ - :returns: The absolute URL of the Worker resource - :rtype: unicode + :returns: The fetched WorkerInstance """ - return self._properties['url'] + payload, _, _ = await self._fetch_async() + return WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - @property - def links(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: The URLs of related resources - :rtype: unicode - """ - return self._properties['links'] + Asynchronous coroutine to fetch the WorkerInstance and return response metadata - def fetch(self): - """ - Fetch the WorkerInstance - :returns: The fetched WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.fetch() - - def update(self, activity_sid=values.unset, attributes=values.unset, - friendly_name=values.unset, - reject_pending_reservations=values.unset): + payload, status_code, headers = await self._fetch_async() + instance = WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - return self._proxy.update( + payload, _, _ = self._update( + if_match=if_match, activity_sid=activity_sid, attributes=attributes, friendly_name=friendly_name, reject_pending_reservations=reject_pending_reservations, ) + return WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - def delete(self): + def update_with_http_info( + 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, + ) -> ApiResponse: """ - Deletes the WorkerInstance + Update the WorkerInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) + instance = WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._proxy.delete() + Asynchronous coroutine to update the WorkerInstance - @property - def real_time_statistics(self): + :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 """ - Access the real_time_statistics + payload, _, _ = await self._update_async( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) + return WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkerInstance and return response metadata + + :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: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsList + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.real_time_statistics + payload, status_code, headers = await self._update_async( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) + instance = WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def cumulative_statistics(self): + def reservations(self) -> ReservationList: """ - Access the cumulative_statistics + Access the reservations + """ + if self._reservations is None: + self._reservations = ReservationList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._reservations - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList + @property + def worker_channels(self) -> WorkerChannelList: + """ + Access the worker_channels """ - return self._proxy.cumulative_statistics + if self._worker_channels is None: + self._worker_channels = WorkerChannelList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._worker_channels @property - def statistics(self): + 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 - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsList + def __repr__(self) -> str: """ - return self._proxy.statistics + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkerPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WorkerInstance: + """ + Build an instance of WorkerInstance + + :param payload: Payload response from the API + """ + + return WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class WorkerList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkerList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workers to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers".format(**self._solution) + + self._cumulative_statistics: Optional[WorkersCumulativeStatisticsList] = None + self._real_time_statistics: Optional[WorkersRealTimeStatisticsList] = None + self._statistics: Optional[WorkersStatisticsList] = None + + def _create( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> WorkerInstance: + """ + Create the WorkerInstance + + :param friendly_name: A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. + :param activity_sid: The SID of a valid Activity that will describe the new Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker's initial state is the `default_activity_sid` configured on the Workspace. + :param attributes: A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + + :returns: The created WorkerInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + activity_sid=activity_sid, + attributes=attributes, + ) + return WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def create_with_http_info( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the WorkerInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + activity_sid=activity_sid, + attributes=attributes, + ) + instance = WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> WorkerInstance: + """ + Asynchronously create the WorkerInstance + + :param friendly_name: A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. + :param activity_sid: The SID of a valid Activity that will describe the new Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker's initial state is the `default_activity_sid` configured on the Workspace. + :param attributes: A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + + :returns: The created WorkerInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + activity_sid=activity_sid, + attributes=attributes, + ) + return WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_with_http_info_async( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WorkerInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + activity_sid=activity_sid, + attributes=attributes, + ) + instance = WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WorkerInstance]: + """ + Streams WorkerInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WorkerInstance]: + """ + Asynchronously streams WorkerInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams WorkerInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams WorkerInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkerInstance]: + """ + Lists WorkerInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkerInstance]: + """ + Asynchronously lists WorkerInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists WorkerInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists WorkerInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkerPage: + """ + Retrieve a single page of WorkerInstance records from the API. + Request is executed immediately + + :param activity_name: The `activity_name` of the Worker resources to read. + :param activity_sid: The `activity_sid` of the Worker resources to read. + :param available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param friendly_name: The `friendly_name` of the Worker resources to read. + :param target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param ordering: Sorting parameter for Workers + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkerInstance + """ + data = values.of( + { + "ActivityName": activity_name, + "ActivitySid": activity_sid, + "Available": available, + "FriendlyName": friendly_name, + "TargetWorkersExpression": target_workers_expression, + "TaskQueueName": task_queue_name, + "TaskQueueSid": task_queue_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkerPage(self._version, response, solution=self._solution) + + async def page_async( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkerPage: + """ + Asynchronously retrieve a single page of WorkerInstance records from the API. + Request is executed immediately + + :param activity_name: The `activity_name` of the Worker resources to read. + :param activity_sid: The `activity_sid` of the Worker resources to read. + :param available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param friendly_name: The `friendly_name` of the Worker resources to read. + :param target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param ordering: Sorting parameter for Workers + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkerInstance + """ + data = values.of( + { + "ActivityName": activity_name, + "ActivitySid": activity_sid, + "Available": available, + "FriendlyName": friendly_name, + "TargetWorkersExpression": target_workers_expression, + "TaskQueueName": task_queue_name, + "TaskQueueSid": task_queue_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkerPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with WorkerPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WorkerPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with WorkerPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WorkerPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> WorkerPage: + """ + Retrieve a specific page of WorkerInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkerInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WorkerPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> WorkerPage: + """ + Asynchronously retrieve a specific page of WorkerInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkerInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkerPage(self._version, response, solution=self._solution) @property - def reservations(self): + def cumulative_statistics(self) -> WorkersCumulativeStatisticsList: """ - Access the reservations + 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.reservation.ReservationList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationList + @property + def real_time_statistics(self) -> WorkersRealTimeStatisticsList: """ - return self._proxy.reservations + Access the real_time_statistics + """ + if self._real_time_statistics is None: + self._real_time_statistics = WorkersRealTimeStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._real_time_statistics @property - def worker_channels(self): + def statistics(self) -> WorkersStatisticsList: """ - Access the worker_channels + Access the statistics + """ + if self._statistics is None: + self._statistics = WorkersStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._statistics - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelList + def get(self, sid: str) -> WorkerContext: """ - return self._proxy.worker_channels + Constructs a WorkerContext + + :param sid: The SID of the Worker resource to update. + """ + return WorkerContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> WorkerContext: + """ + Constructs a WorkerContext + + :param sid: The SID of the Worker resource to update. + """ + return WorkerContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 9ab08512e3..227b2b83d7 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/reservation.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/reservation.py @@ -1,429 +1,29 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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) - - 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. - - :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) - - :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) - - page = self.page(reservation_status=reservation_status, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, reservation_status=values.unset, limit=None, page_size=None): - """ - 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) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance] - """ - return list(self.stream(reservation_status=reservation_status, limit=limit, page_size=page_size, )) - - def page(self, reservation_status=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of ReservationInstance records from the API. - Request is executed immediately - - :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 - """ - 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) - - def get_page(self, target_url): - """ - Retrieve a specific page of ReservationInstance records from the API. - Request is executed immediately - - :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 - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ReservationPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a ReservationContext - - :param sid: The SID of the WorkerReservation resource to fetch - - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext - """ - return ReservationContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a ReservationContext - - :param sid: The SID of the WorkerReservation resource to fetch - - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext - """ - return ReservationContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], - sid=sid, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ReservationPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - 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 - - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationPage - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationPage - """ - super(ReservationPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of 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 - """ - return ReservationInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ReservationContext(InstanceContext): - """ """ - - def __init__(self, version, workspace_sid, worker_sid, sid): - """ - Initialize the ReservationContext - - :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 - - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext - """ - super(ReservationContext, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'worker_sid': worker_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/Workers/{worker_sid}/Reservations/{sid}'.format(**self._solution) - - def fetch(self): - """ - 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, ) - - return ReservationInstance( - self._version, - payload, - 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): - """ - 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 - - :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, ) - - return ReservationInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_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 ReservationInstance(InstanceResource): - """ """ - - class Status(object): - PENDING = "pending" - ACCEPTED = "accepted" - REJECTED = "rejected" - TIMEOUT = "timeout" - CANCELED = "canceled" - RESCINDED = "rescinded" - WRAPPING = "wrapping" - COMPLETED = "completed" class CallStatus(object): INITIATED = "initiated" @@ -440,245 +40,240 @@ class ConferenceEvent(object): HOLD = "hold" SPEAKER = "speaker" - def __init__(self, version, payload, workspace_sid, worker_sid, sid=None): - """ - Initialize the ReservationInstance - - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance - """ - super(ReservationInstance, self).__init__(version) + class Status(object): + PENDING = "pending" + ACCEPTED = "accepted" + REJECTED = "rejected" + TIMEOUT = "timeout" + CANCELED = "canceled" + RESCINDED = "rescinded" + WRAPPING = "wrapping" + COMPLETED = "completed" - # 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'), - } + """ + :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") - # Context - self._context = None self._solution = { - 'workspace_sid': workspace_sid, - 'worker_sid': worker_sid, - 'sid': sid or self._properties['sid'], + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + "sid": sid or self.sid, } + self._context: Optional[ReservationContext] = None + @property - def _proxy(self): + def _proxy(self) -> "ReservationContext": """ Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + performing various actions. All instance actions are proxied to the context :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'], + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_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): + def fetch(self) -> "ReservationInstance": """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + Fetch the ReservationInstance - @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 reservation_status(self): - """ - :returns: The current status of the reservation - :rtype: ReservationInstance.Status + :returns: The fetched ReservationInstance """ - return self._properties['reservation_status'] + return self._proxy.fetch() - @property - def sid(self): + async def fetch_async(self) -> "ReservationInstance": """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Asynchronous coroutine to fetch the ReservationInstance - @property - def task_sid(self): - """ - :returns: The SID of the reserved Task resource - :rtype: unicode - """ - return self._properties['task_sid'] - @property - def worker_name(self): - """ - :returns: The friendly_name of the Worker that is reserved - :rtype: unicode + :returns: The fetched ReservationInstance """ - return self._properties['worker_name'] + return await self._proxy.fetch_async() - @property - def worker_sid(self): + def fetch_with_http_info(self) -> ApiResponse: """ - :returns: The SID of the reserved Worker resource - :rtype: unicode - """ - return self._properties['worker_sid'] + Fetch the ReservationInstance with HTTP info - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace that this worker is contained within. - :rtype: unicode - """ - return self._properties['workspace_sid'] - @property - def url(self): - """ - :returns: The absolute URL of the WorkerReservation resource - :rtype: unicode + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['url'] + return self._proxy.fetch_with_http_info() - @property - def links(self): - """ - :returns: The URLs of related resources - :rtype: unicode + async def fetch_with_http_info_async(self) -> ApiResponse: """ - return self._properties['links'] + Asynchronous coroutine to fetch the ReservationInstance with HTTP info - def fetch(self): - """ - Fetch the ReservationInstance - :returns: The fetched ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.fetch() - - 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): + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> "ReservationInstance": """ Update the ReservationInstance - :param 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 + :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 """ return self._proxy.update( + if_match=if_match, reservation_status=reservation_status, worker_activity_sid=worker_activity_sid, instruction=instruction, @@ -730,14 +325,2191 @@ def update(self, reservation_status=values.unset, post_work_activity_sid=post_work_activity_sid, end_conference_on_customer_exit=end_conference_on_customer_exit, beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> "ReservationInstance": + """ + Asynchronous coroutine to update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for the reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: The timeout for call when executing a Dequeue instruction. + :param dequeue_to: The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction. + :param call_timeout: The timeout for a call when executing a Call instruction. + :param call_to: The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: The timeout for a call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Defaults to `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + return await self._proxy.update_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ReservationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ReservationInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ReservationContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str, sid: str): + """ + Initialize the ReservationContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerReservation resources to update. + :param worker_sid: The SID of the reserved Worker resource with the WorkerReservation resources to update. + :param sid: The SID of the WorkerReservation resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Reservations/{sid}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ReservationInstance: + """ + Fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + payload, _, _ = self._fetch() + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ReservationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ReservationInstance: + """ + Asynchronous coroutine to fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + payload, _, _ = await self._fetch_async() + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ReservationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for the reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: The timeout for call when executing a Dequeue instruction. + :param dequeue_to: The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction. + :param call_timeout: The timeout for a call when executing a Call instruction. + :param call_to: The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: The timeout for a call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Defaults to `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + payload, _, _ = self._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, + ) + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ReservationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Asynchronous coroutine to update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for the reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: The timeout for call when executing a Dequeue instruction. + :param dequeue_to: The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction. + :param call_timeout: The timeout for a call when executing a Call instruction. + :param call_to: The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: The timeout for a call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Defaults to `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + payload, _, _ = await self._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, + ) + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ReservationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 ReservationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ReservationInstance: + """ + Build an instance of ReservationInstance + + :param payload: Payload response from the API + """ + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ReservationList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): + """ + Initialize the ReservationList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerReservation resources to read. + :param worker_sid: The SID of the reserved Worker resource with the WorkerReservation resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Reservations".format( + **self._solution + ) + ) + + def stream( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ReservationInstance]: + """ + Streams ReservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + reservation_status=reservation_status, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ReservationInstance]: + """ + Asynchronously streams ReservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + reservation_status=reservation_status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ReservationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + reservation_status=reservation_status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ReservationInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + reservation_status=reservation_status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ReservationInstance]: + """ + Lists ReservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + reservation_status=reservation_status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ReservationInstance]: + """ + Asynchronously lists ReservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + reservation_status=reservation_status, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ReservationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + reservation_status=reservation_status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ReservationInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + reservation_status=reservation_status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ReservationPage: + """ + Retrieve a single page of ReservationInstance records from the API. + Request is executed immediately + + :param reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ReservationInstance + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, solution=self._solution) + + async def page_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ReservationPage: + """ + Asynchronously retrieve a single page of ReservationInstance records from the API. + Request is executed immediately + + :param reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ReservationInstance + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ReservationPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ReservationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ReservationPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ReservationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ReservationPage: + """ + Retrieve a specific page of ReservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ReservationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ReservationPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ReservationPage: + """ + Asynchronously retrieve a specific page of ReservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ReservationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ReservationPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> ReservationContext: + """ + Constructs a ReservationContext + + :param sid: The SID of the WorkerReservation resource to update. + """ + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ReservationContext: + """ + Constructs a ReservationContext + + :param sid: The SID of the WorkerReservation resource to update. + """ + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=sid, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 e0913e5cc0..61d407fd38 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py @@ -1,461 +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, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +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") - def __init__(self, version, workspace_sid, worker_sid): - """ - Initialize the WorkerChannelList + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + "sid": sid or self.sid, + } - :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 + self._context: Optional[WorkerChannelContext] = None - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelList + @property + def _proxy(self) -> "WorkerChannelContext": """ - super(WorkerChannelList, 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, 'worker_sid': worker_sid, } - self._uri = '/Workspaces/{workspace_sid}/Workers/{worker_sid}/Channels'.format(**self._solution) + :returns: WorkerChannelContext for this WorkerChannelInstance + """ + if self._context is None: + self._context = WorkerChannelContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def fetch(self) -> "WorkerChannelInstance": """ - Streams WorkerChannelInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Fetch the WorkerChannelInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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] + :returns: The fetched WorkerChannelInstance """ - 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) -> "WorkerChannelInstance": + """ + Asynchronous coroutine to fetch the WorkerChannelInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched WorkerChannelInstance """ - Lists WorkerChannelInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkerChannelInstance with HTTP info - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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] + :returns: ApiResponse with instance, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch_with_http_info() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Retrieve a single page of WorkerChannelInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the WorkerChannelInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_with_http_info_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def update( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> "WorkerChannelInstance": + """ + Update the WorkerChannelInstance - return WorkerChannelPage(self._version, response, 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 get_page(self, target_url): + :returns: The updated WorkerChannelInstance """ - Retrieve a specific page of WorkerChannelInstance records from the API. - Request is executed immediately + return self._proxy.update( + capacity=capacity, + available=available, + ) - :param str target_url: API-generated URL for the requested results page + async def update_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> "WorkerChannelInstance": + """ + Asynchronous coroutine to update the WorkerChannelInstance - :returns: Page of WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelPage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + capacity=capacity, + available=available, ) - return WorkerChannelPage(self._version, response, self._solution) - - def get(self, sid): + def update_with_http_info( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - Constructs a WorkerChannelContext + Update the WorkerChannelInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WorkerChannelContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], - sid=sid, + return self._proxy.update_with_http_info( + capacity=capacity, + available=available, ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - Constructs a WorkerChannelContext + Asynchronous coroutine to update the WorkerChannelInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WorkerChannelContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], - sid=sid, + return await self._proxy.update_with_http_info_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) -> tuple: """ - Build an instance of WorkerChannelInstance + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> 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 """ + payload, _, _ = self._fetch() 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Fetch the WorkerChannelInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: """ - return '' + Internal async helper for fetch operation + Returns: + tuple: (payload, status_code, headers) + """ -class WorkerChannelContext(InstanceContext): - """ """ + headers = values.of({}) + + headers["Accept"] = "application/json" - def __init__(self, version, workspace_sid, worker_sid, sid): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> WorkerChannelInstance: """ - Initialize the WorkerChannelContext + Asynchronous coroutine to fetch the WorkerChannelInstance - :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 - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelContext + :returns: The fetched WorkerChannelInstance """ - super(WorkerChannelContext, self).__init__(version) + payload, _, _ = await self._fetch_async() + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) - # 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) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkerChannelInstance and return response metadata - def fetch(self): + + :returns: ApiResponse with instance, status code, and headers """ - Fetch the WorkerChannelInstance + payload, status_code, headers = await self._fetch_async() + instance = WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: The fetched WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance + def _update( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> WorkerChannelInstance: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Update the WorkerChannelInstance + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: The updated WorkerChannelInstance + """ + payload, _, _ = self._update(capacity=capacity, available=available) 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): + def update_with_http_info( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - Update the WorkerChannelInstance + Update the WorkerChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + capacity=capacity, available=available + ) + instance = WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Capacity": capacity, + "Available": serialize.boolean_to_string(available), + } + ) + headers = values.of({}) - :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 + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> WorkerChannelInstance: + """ + Asynchronous coroutine to update the WorkerChannelInstance + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. :returns: The updated WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance """ - data = values.of({'Capacity': capacity, 'Available': available, }) + payload, _, _ = await self._update_async(capacity=capacity, available=available) + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + async def update_with_http_info_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkerChannelInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + capacity=capacity, available=available + ) + instance = WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 WorkerChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WorkerChannelInstance: + """ + Build an instance of WorkerChannelInstance + + :param payload: Payload response from the API + """ return WorkerChannelInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], - sid=self._solution['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) + return "" -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'), - } +class WorkerChannelList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): + """ + Initialize the WorkerChannelList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerChannels to read. + :param worker_sid: The SID of the Worker with the WorkerChannels to read. - # Context - self._context = None + """ + super().__init__(version) + + # Path Solution self._solution = { - 'workspace_sid': workspace_sid, - 'worker_sid': worker_sid, - 'sid': sid or self._properties['sid'], + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, } + self._uri = "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Channels".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WorkerChannelInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: WorkerChannelContext for this WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelContext - """ - 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 + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def account_sid(self): + :returns: Generator that will yield up to limit results """ - :returns: The 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[WorkerChannelInstance]: """ - return self._properties['account_sid'] + 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 assigned_tasks(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 total number of Tasks assigned to Worker for the TaskChannel type - :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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['assigned_tasks'] + Streams WorkerChannelInstance and returns headers from first page - @property - def available(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: Whether the Worker should receive Tasks of the TaskChannel type - :rtype: bool + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - return self._properties['available'] + Asynchronously streams WorkerChannelInstance and returns headers from first page - @property - def available_capacity_percentage(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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The current available capacity between 0 to 100 for the TaskChannel - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkerChannelInstance]: """ - return self._properties['available_capacity_percentage'] + 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 configured_capacity(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 current configured capacity for the WorkerChannel - :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['configured_capacity'] + 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 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_created'] + Lists WorkerChannelInstance and returns headers from first page - @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: ApiResponse with list of instances, status code, and headers """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously lists WorkerChannelInstance and returns headers from first page - @property - def 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: ApiResponse with list of instances, status code, and headers """ - :returns: The unique string that identifies the resource - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['sid'] + Retrieve a single page of WorkerChannelInstance records from the API. + Request is executed immediately - @property - def task_channel_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 TaskChannel - :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, solution=self._solution) + + async def 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['task_channel_sid'] + Asynchronously retrieve a single page of WorkerChannelInstance records from the API. + Request is executed immediately - @property - def task_channel_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 WorkerChannelInstance """ - :returns: The unique name of the TaskChannel, such as 'voice' or 'sms' - :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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['task_channel_unique_name'] + Retrieve a single page with response metadata - @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: ApiResponse with WorkerChannelPage, status code, and headers """ - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WorkerChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['worker_sid'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with WorkerChannelPage, status code, and headers """ - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WorkerChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..f2fbcd5c34 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py @@ -1,288 +1,442 @@ -# 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.api_response import ApiResponse 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): - """ """ - def __init__(self, version, workspace_sid, worker_sid): - """ - Initialize the WorkerStatisticsList +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, + } - :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 + self._context: Optional[WorkerStatisticsContext] = None - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsList + @property + def _proxy(self) -> "WorkerStatisticsContext": """ - super(WorkerStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'worker_sid': worker_sid, } + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def get(self): + :returns: WorkerStatisticsContext for this WorkerStatisticsInstance """ - Constructs a WorkerStatisticsContext + if self._context is None: + self._context = WorkerStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + return self._context - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext + 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": """ - return WorkerStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], - ) + Fetch the WorkerStatisticsInstance - def __call__(self): - """ - Constructs a 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: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext + :returns: The fetched WorkerStatisticsInstance """ - return WorkerStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], + return self._proxy.fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + 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": """ - return '' + 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`. -class WorkerStatisticsPage(Page): - """ """ + :returns: The fetched WorkerStatisticsInstance + """ + return await self._proxy.fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) - def __init__(self, version, response, solution): + def fetch_with_http_info( + 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, + ) -> ApiResponse: """ - Initialize the WorkerStatisticsPage + Fetch the WorkerStatisticsInstance with HTTP info - :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 + :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.WorkerStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsPage + :returns: ApiResponse with instance, status code, and headers """ - super(WorkerStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) - def get_instance(self, payload): + async def fetch_with_http_info_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, + ) -> ApiResponse: """ - Build an instance of WorkerStatisticsInstance + Asynchronous coroutine to fetch the WorkerStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WorkerStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], + return await self._proxy.fetch_with_http_info_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 WorkerStatisticsContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid, worker_sid): + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): """ Initialize the WorkerStatisticsContext - :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 - - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerChannel to fetch. + :param worker_sid: The SID of the Worker with the WorkerChannel to fetch. """ - super(WorkerStatisticsContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'worker_sid': worker_sid, } - self._uri = '/Workspaces/{workspace_sid}/Workers/{worker_sid}/Statistics'.format(**self._solution) + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Statistics".format( + **self._solution + ) + ) - def fetch(self, minutes=values.unset, start_date=values.unset, - end_date=values.unset, task_channel=values.unset): + 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, + ) -> tuple: """ - Fetch the WorkerStatisticsInstance + Internal helper for fetch operation - :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 + Returns: + tuple: (payload, status_code, headers) + """ - :returns: The fetched WorkerStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsInstance + params = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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: """ - data = values.of({ - 'Minutes': minutes, - 'StartDate': serialize.iso8601_datetime(start_date), - 'EndDate': serialize.iso8601_datetime(end_date), - 'TaskChannel': task_channel, - }) + Fetch the WorkerStatisticsInstance - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + :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 + """ + payload, _, _ = self._fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) 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 fetch_with_http_info( + 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, + ) -> ApiResponse: """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Fetch the WorkerStatisticsInstance and return response metadata + :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`. -class WorkerStatisticsInstance(InstanceResource): - """ """ + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) + instance = WorkerStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __init__(self, version, payload, 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, + ) -> tuple: """ - Initialize the WorkerStatisticsInstance + Internal async helper for fetch operation - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - 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'), - } + params = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + } + ) - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'worker_sid': worker_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: WorkerStatisticsContext for this WorkerStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext - """ - if self._context is None: - self._context = WorkerStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], - ) - return self._context + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + 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: """ - return self._properties['account_sid'] + Asynchronous coroutine to fetch the WorkerStatisticsInstance - @property - def cumulative(self): + :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 """ - :returns: An object that contains the cumulative statistics for the Worker - :rtype: dict + payload, _, _ = await self._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) + return WorkerStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + + async def fetch_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['cumulative'] + Asynchronous coroutine to fetch the WorkerStatisticsInstance and return response metadata - @property - def worker_sid(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Worker that contains the WorkerChannel - :rtype: unicode + payload, status_code, headers = await self._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) + instance = WorkerStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - return self._properties['worker_sid'] + Provide a friendly representation - @property - def workspace_sid(self): + :returns: Machine friendly representation """ - :returns: The SID of the Workspace that contains the WorkerChannel - :rtype: unicode + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkerStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): """ - return self._properties['workspace_sid'] + Initialize the WorkerStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerChannel to fetch. + :param worker_sid: The SID of the Worker with the WorkerChannel to fetch. - @property - def url(self): """ - :returns: The absolute URL of the WorkerChannel statistics resource - :rtype: unicode + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } + + def get(self) -> WorkerStatisticsContext: """ - return self._properties['url'] + Constructs a WorkerStatisticsContext - def fetch(self, minutes=values.unset, start_date=values.unset, - end_date=values.unset, task_channel=values.unset): """ - Fetch the WorkerStatisticsInstance + return WorkerStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) - :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 + def __call__(self) -> WorkerStatisticsContext: + """ + 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..dbcce53c8c 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,456 @@ -# 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.api_response import ApiResponse 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 WorkersCumulativeStatisticsList(ListResource): - """ """ +class WorkersCumulativeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + :ivar start_time: The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar end_time: The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar activity_durations: The minimum, average, maximum, and total time (in seconds) that Workers spent in each Activity. + :ivar reservations_created: The total number of Reservations that were created. + :ivar reservations_accepted: The total number of Reservations that were accepted. + :ivar reservations_rejected: The total number of Reservations that were rejected. + :ivar reservations_timed_out: The total number of Reservations that were timed out. + :ivar reservations_canceled: The total number of Reservations that were canceled. + :ivar reservations_rescinded: The total number of Reservations that were rescinded. + :ivar workspace_sid: The SID of the Workspace that contains the Workers. + :ivar url: The absolute URL of the Workers statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.activity_durations: Optional[List[Dict[str, object]]] = payload.get( + "activity_durations" + ) + self.reservations_created: Optional[int] = deserialize.integer( + payload.get("reservations_created") + ) + self.reservations_accepted: Optional[int] = deserialize.integer( + payload.get("reservations_accepted") + ) + self.reservations_rejected: Optional[int] = deserialize.integer( + payload.get("reservations_rejected") + ) + self.reservations_timed_out: Optional[int] = deserialize.integer( + payload.get("reservations_timed_out") + ) + self.reservations_canceled: Optional[int] = deserialize.integer( + payload.get("reservations_canceled") + ) + self.reservations_rescinded: Optional[int] = deserialize.integer( + payload.get("reservations_rescinded") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") - def __init__(self, version, workspace_sid): - """ - Initialize the WorkersCumulativeStatisticsList + self._solution = { + "workspace_sid": workspace_sid, + } - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace that contains the Workers + self._context: Optional[WorkersCumulativeStatisticsContext] = None - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList + @property + def _proxy(self) -> "WorkersCumulativeStatisticsContext": """ - super(WorkersCumulativeStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def get(self): + :returns: WorkersCumulativeStatisticsContext for this WorkersCumulativeStatisticsInstance """ - Constructs a WorkersCumulativeStatisticsContext + if self._context is None: + self._context = WorkersCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext + 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": """ - return WorkersCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) + Fetch the WorkersCumulativeStatisticsInstance - def __call__(self): - """ - Constructs a WorkersCumulativeStatisticsContext + :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.WorkersCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext + :returns: The fetched WorkersCumulativeStatisticsInstance """ - return WorkersCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, ) - def __repr__(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, + ) -> "WorkersCumulativeStatisticsInstance": """ - Provide a friendly representation + Asynchronous coroutine to fetch the WorkersCumulativeStatisticsInstance - :returns: Machine friendly representation - :rtype: str - """ - return '' + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :returns: The fetched WorkersCumulativeStatisticsInstance + """ + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) -class WorkersCumulativeStatisticsPage(Page): - """ """ - - def __init__(self, version, response, solution): + def fetch_with_http_info( + 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, + ) -> ApiResponse: """ - Initialize the WorkersCumulativeStatisticsPage + Fetch the WorkersCumulativeStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - super(WorkersCumulativeStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) - def get_instance(self, payload): + async def fetch_with_http_info_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, + ) -> ApiResponse: """ - Build an instance of WorkersCumulativeStatisticsInstance + Asynchronous coroutine to fetch the WorkersCumulativeStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WorkersCumulativeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], + return await self._proxy.fetch_with_http_info_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: 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, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = 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" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) - 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._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) + return WorkersCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + def fetch_with_http_info( + 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, + ) -> ApiResponse: + """ + Fetch the WorkersCumulativeStatisticsInstance and return response metadata - return WorkersCumulativeStatisticsInstance( + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) + instance = WorkersCumulativeStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], + workspace_sid=self._solution["workspace_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(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, + ) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + params = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + } + ) -class WorkersCumulativeStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid): - """ - 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'), - } + headers = values.of({}) - # Context - self._context = None - self._solution = {'workspace_sid': workspace_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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - :returns: WorkersCumulativeStatisticsContext for this WorkersCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext + 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: """ - if self._context is None: - self._context = WorkersCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._context + Asynchronous coroutine to fetch the WorkersCumulativeStatisticsInstance - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - @property - def start_time(self): - """ - :returns: The beginning of the interval during which these statistics were calculated - :rtype: datetime + :returns: The fetched WorkersCumulativeStatisticsInstance """ - return self._properties['start_time'] + payload, _, _ = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) + return WorkersCumulativeStatisticsInstance( + 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_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['end_time'] + Asynchronous coroutine to fetch the WorkersCumulativeStatisticsInstance and return response metadata - @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'] + :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`. - @property - def reservations_created(self): + :returns: ApiResponse with instance, status code, and headers """ - :returns: The total number of Reservations that were created - :rtype: unicode - """ - return self._properties['reservations_created'] + payload, status_code, headers = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) + instance = WorkersCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def reservations_accepted(self): - """ - :returns: The total number of Reservations that were accepted - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['reservations_accepted'] + Provide a friendly representation - @property - def reservations_rejected(self): - """ - :returns: The total number of Reservations that were rejected - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['reservations_rejected'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - @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'] +class WorkersCumulativeStatisticsList(ListResource): - @property - def reservations_rescinded(self): - """ - :returns: The total number of Reservations that were rescinded - :rtype: unicode + def __init__(self, version: Version, workspace_sid: str): """ - return self._properties['reservations_rescinded'] + Initialize the WorkersCumulativeStatisticsList - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace that contains the Workers - :rtype: unicode - """ - return self._properties['workspace_sid'] + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. - @property - def url(self): """ - :returns: The absolute URL of the Workers statistics resource - :rtype: unicode + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkersCumulativeStatisticsContext: """ - return self._properties['url'] + Constructs a WorkersCumulativeStatisticsContext - def fetch(self, end_date=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset): """ - Fetch the WorkersCumulativeStatisticsInstance + return WorkersCumulativeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) - :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 + def __call__(self) -> WorkersCumulativeStatisticsContext: + """ + 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..9efc95193a 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,325 @@ -# 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.api_response import ApiResponse 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): - """ """ +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") - def __init__(self, version, workspace_sid): - """ - Initialize the WorkersRealTimeStatisticsList + self._solution = { + "workspace_sid": workspace_sid, + } - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace that contains the Workers + 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) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def get(self): + :returns: WorkersRealTimeStatisticsContext for this WorkersRealTimeStatisticsInstance """ - Constructs a WorkersRealTimeStatisticsContext + if self._context is None: + self._context = WorkersRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsContext + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkersRealTimeStatisticsInstance": """ - return WorkersRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) + Fetch the WorkersRealTimeStatisticsInstance - def __call__(self): - """ - Constructs a 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: 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 __repr__(self): + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkersRealTimeStatisticsInstance": """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' + Asynchronous coroutine to fetch the WorkersRealTimeStatisticsInstance + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. -class WorkersRealTimeStatisticsPage(Page): - """ """ + :returns: The fetched WorkersRealTimeStatisticsInstance + """ + return await self._proxy.fetch_async( + task_channel=task_channel, + ) - def __init__(self, version, response, solution): + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: """ - Initialize the WorkersRealTimeStatisticsPage + Fetch the WorkersRealTimeStatisticsInstance with HTTP info - :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 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.WorkersRealTimeStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsPage + :returns: ApiResponse with instance, status code, and headers """ - super(WorkersRealTimeStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info( + task_channel=task_channel, + ) - def get_instance(self, payload): + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: """ - Build an instance of WorkersRealTimeStatisticsInstance + Asynchronous coroutine to fetch the WorkersRealTimeStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WorkersRealTimeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], + return await self._proxy.fetch_with_http_info_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 WorkersRealTimeStatisticsContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkersRealTimeStatisticsContext - :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_real_time_statistics.WorkersRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsContext + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. """ - super(WorkersRealTimeStatisticsContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/Workers/RealTimeStatistics'.format(**self._solution) + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/RealTimeStatistics".format( + **self._solution + ) - def fetch(self, task_channel=values.unset): + def _fetch(self, task_channel: Union[str, object] = values.unset) -> tuple: """ - Fetch the WorkersRealTimeStatisticsInstance + Internal helper for fetch operation - :param unicode task_channel: Only calculate real-time statistics on this TaskChannel + Returns: + tuple: (payload, status_code, headers) + """ - :returns: The fetched WorkersRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsInstance + params = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> WorkersRealTimeStatisticsInstance: """ - data = values.of({'TaskChannel': task_channel, }) + Fetch the WorkersRealTimeStatisticsInstance - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + :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 + """ + payload, _, _ = self._fetch(task_channel=task_channel) return WorkersRealTimeStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], + workspace_sid=self._solution["workspace_sid"], ) - def __repr__(self): + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: """ - Provide a friendly representation + Fetch the WorkersRealTimeStatisticsInstance and return response metadata - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(task_channel=task_channel) + instance = WorkersRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) -class WorkersRealTimeStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid): + async def _fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> tuple: """ - Initialize the WorkersRealTimeStatisticsInstance + Internal async helper for fetch operation - :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: + tuple: (payload, status_code, headers) """ - 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'), - } + params = 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: WorkersRealTimeStatisticsContext for this WorkersRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsContext - """ - if self._context is None: - self._context = WorkersRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._context + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> WorkersRealTimeStatisticsInstance: """ - return self._properties['account_sid'] + Asynchronous coroutine to fetch the WorkersRealTimeStatisticsInstance - @property - def activity_statistics(self): + :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 """ - :returns: The number of current Workers by Activity - :rtype: dict + payload, _, _ = await self._fetch_async(task_channel=task_channel) + return WorkersRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: """ - return self._properties['activity_statistics'] + Asynchronous coroutine to fetch the WorkersRealTimeStatisticsInstance and return response metadata - @property - def total_workers(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The total number of Workers - :rtype: unicode + payload, status_code, headers = await self._fetch_async( + task_channel=task_channel + ) + instance = WorkersRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - return self._properties['total_workers'] + Provide a friendly representation - @property - def workspace_sid(self): + :returns: Machine friendly representation """ - :returns: The SID of the Workspace that contains the Workers - :rtype: unicode + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class WorkersRealTimeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): """ - return self._properties['workspace_sid'] + Initialize the WorkersRealTimeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. - @property - def url(self): """ - :returns: The absolute URL of the Workers statistics resource - :rtype: unicode + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkersRealTimeStatisticsContext: """ - return self._properties['url'] + Constructs a WorkersRealTimeStatisticsContext - def fetch(self, task_channel=values.unset): """ - Fetch the WorkersRealTimeStatisticsInstance + return WorkersRealTimeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) - :param unicode task_channel: Only calculate real-time statistics on this TaskChannel + def __call__(self) -> WorkersRealTimeStatisticsContext: + """ + 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..8a3a21b6bb 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py @@ -1,290 +1,504 @@ -# 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.api_response import ApiResponse 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 + 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: WorkersStatisticsContext for this WorkersStatisticsInstance + """ + if self._context is None: + self._context = WorkersStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsList + 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": """ - super(WorkersStatisticsList, self).__init__(version) + Fetch the WorkersStatisticsInstance - # 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_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 get(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, + ) - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext - """ - return WorkersStatisticsContext(self._version, workspace_sid=self._solution['workspace_sid'], ) + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> "WorkersStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkersStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - def __call__(self): + :returns: The fetched WorkersStatisticsInstance """ - Constructs a WorkersStatisticsContext + 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, + ) - :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'], ) + def fetch_with_http_info( + 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, + ) -> ApiResponse: + """ + Fetch the WorkersStatisticsInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkersStatisticsInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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): - """ - Build an instance of WorkersStatisticsInstance + def _fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskQueueSid": task_queue_sid, + "TaskQueueName": task_queue_name, + "FriendlyName": friendly_name, + "TaskChannel": task_channel, + } + ) - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsInstance - """ - return WorkersStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) - def __repr__(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: """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' + 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`. -class WorkersStatisticsContext(InstanceContext): - """ """ - - def __init__(self, version, workspace_sid): + :returns: The fetched WorkersStatisticsInstance """ - Initialize the WorkersStatisticsContext + payload, _, _ = self._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 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 + def fetch_with_http_info( + 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, + ) -> ApiResponse: + """ + Fetch the WorkersStatisticsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = WorkersStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskQueueSid": task_queue_sid, + "TaskQueueName": task_queue_name, + "FriendlyName": friendly_name, + "TaskChannel": task_channel, + } + ) - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext - """ - super(WorkersStatisticsContext, self).__init__(version) + headers = values.of({}) - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/Workers/Statistics'.format(**self._solution) + headers["Accept"] = "application/json" - 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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - :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 + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkersStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkersStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. :returns: The fetched WorkersStatisticsInstance - :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._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, + ) return WorkersStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], + workspace_sid=self._solution["workspace_sid"], + ) + + async def fetch_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkersStatisticsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = WorkersStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class WorkersStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid): - """ - Initialize the WorkersStatisticsInstance - :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 - 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 605f310795..547db90579 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py @@ -1,606 +1,1442 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. + return self._proxy.delete() - :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) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WorkflowInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance] + + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(friendly_name=friendly_name, page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WorkflowInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, friendly_name=values.unset, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists WorkflowInstance 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.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WorkflowInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(friendly_name=friendly_name, limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, friendly_name=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch(self) -> "WorkflowInstance": """ - Retrieve a single page of WorkflowInstance records from the API. - Request is executed immediately + 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 self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "WorkflowInstance": + """ + Asynchronous coroutine to fetch the WorkflowInstance - return WorkflowPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched WorkflowInstance """ - Retrieve a specific page of WorkflowInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkflowInstance with HTTP info - :returns: Page of WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() - return WorkflowPage(self._version, response, self._solution) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowInstance with HTTP info - def create(self, friendly_name, configuration, - assignment_callback_url=values.unset, - fallback_assignment_callback_url=values.unset, - task_reservation_timeout=values.unset): + + :returns: ApiResponse with instance, status code, and headers """ - Create the WorkflowInstance + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> "WorkflowInstance": + """ + Update the WorkflowInstance - :param 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 + :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 created WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance + :returns: The updated WorkflowInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Configuration': configuration, - 'AssignmentCallbackUrl': assignment_callback_url, - 'FallbackAssignmentCallbackUrl': fallback_assignment_callback_url, - 'TaskReservationTimeout': task_reservation_timeout, - }) + 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, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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. - return WorkflowInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + :returns: The updated WorkflowInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + configuration=configuration, + task_reservation_timeout=task_reservation_timeout, + re_evaluate_tasks=re_evaluate_tasks, + ) - def get(self, sid): + def update_with_http_info( + 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, + ) -> ApiResponse: """ - Constructs a WorkflowContext + Update the WorkflowInstance with HTTP info - :param sid: The SID of the resource + :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: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext + :returns: ApiResponse with instance, status code, and headers """ - return WorkflowContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + 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, + ) - def __call__(self, sid): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Constructs a WorkflowContext + Asynchronous coroutine to update the WorkflowInstance with HTTP info - :param sid: The SID of the resource + :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: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext + :returns: ApiResponse with instance, status code, and headers """ - return WorkflowContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + configuration=configuration, + task_reservation_timeout=task_reservation_timeout, + re_evaluate_tasks=re_evaluate_tasks, + ) + + @property + def cumulative_statistics(self) -> WorkflowCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + return self._proxy.cumulative_statistics + + @property + def real_time_statistics(self) -> WorkflowRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + return self._proxy.real_time_statistics - def __repr__(self): + @property + def statistics(self) -> WorkflowStatisticsList: + """ + Access the statistics + """ + return self._proxy.statistics + + 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) -> tuple: """ - Build an instance of WorkflowInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance + def delete(self) -> bool: """ - return WorkflowInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + Deletes the WorkflowInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the WorkflowInstance and return response metadata -class WorkflowContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, workspace_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the WorkflowContext + Internal async helper for delete operation - :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: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext + async def delete_async(self) -> bool: """ - super(WorkflowContext, self).__init__(version) + Asynchronous coroutine that deletes the WorkflowInstance - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/Workflows/{sid}'.format(**self._solution) - # Dependents - self._statistics = None - self._real_time_statistics = None - self._cumulative_statistics = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WorkflowInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> WorkflowInstance: """ Fetch the WorkflowInstance + :returns: The fetched WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkflowInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> WorkflowInstance: + """ + Asynchronous coroutine to fetch the WorkflowInstance + + + :returns: The fetched WorkflowInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._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 WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the WorkflowInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> WorkflowInstance: + """ + Asynchronous coroutine to update the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + :returns: The updated WorkflowInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + configuration=configuration, + task_reservation_timeout=task_reservation_timeout, + re_evaluate_tasks=re_evaluate_tasks, + ) return WorkflowInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Deletes the WorkflowInstance + Asynchronous coroutine to update the WorkflowInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._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, + ) + instance = WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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'), - } +class WorkflowPage(Page): - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } + def get_instance(self, payload: Dict[str, Any]) -> WorkflowInstance: + """ + Build an instance of WorkflowInstance - @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 - :returns: WorkflowContext for this WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext + return WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: """ - if self._context is None: - self._context = WorkflowContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - return self._context + 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 WorkflowList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): """ - return self._properties['account_sid'] + Initialize the WorkflowList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to read. - @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 + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workflows".format(**self._solution) + + def _create( + self, + friendly_name: str, + configuration: str, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._properties['assignment_callback_url'] + Create the WorkflowInstance - @property - def configuration(self): + :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 """ - :returns: A JSON string that contains the Workflow's configuration - :rtype: unicode + payload, _, _ = self._create( + friendly_name=friendly_name, + configuration=configuration, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + task_reservation_timeout=task_reservation_timeout, + ) + return WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['configuration'] + Create the WorkflowInstance and return response metadata - @property - def date_created(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + payload, status_code, headers = self._create( + friendly_name=friendly_name, + configuration=configuration, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + task_reservation_timeout=task_reservation_timeout, + ) + instance = WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - return self._properties['date_created'] + Asynchronously create the WorkflowInstance - @property - def date_updated(self): + :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 """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + configuration=configuration, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + task_reservation_timeout=task_reservation_timeout, + ) + return WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously create the WorkflowInstance and return response metadata - @property - def document_content_type(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The MIME type of the document - :rtype: unicode + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + configuration=configuration, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + task_reservation_timeout=task_reservation_timeout, + ) + instance = WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WorkflowInstance]: """ - return self._properties['document_content_type'] + 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. - @property - def fallback_assignment_callback_url(self): + :param str friendly_name: The `friendly_name` of the Workflow resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WorkflowInstance]: """ - :returns: The URL that we call when a call to the `assignment_callback_url` fails - :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['fallback_assignment_callback_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 friendly_name(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The string that you assigned to describe the Workflow resource - :rtype: unicode + Streams WorkflowInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, page_size=limits["page_size"] + ) - @property - def sid(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Asynchronously streams WorkflowInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['sid'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) - @property - def task_reservation_timeout(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkflowInstance]: """ - :returns: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker - :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 self._properties['task_reservation_timeout'] - @property - def workspace_sid(self): + 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]: """ - :returns: The SID of the Workspace that contains the Workflow - :rtype: unicode + 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 self._properties['workspace_sid'] - @property - def url(self): + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The absolute URL of the Workflow resource - :rtype: unicode + Lists WorkflowInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers """ - return self._properties['url'] + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def links(self): + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The URLs of related resources - :rtype: unicode + Asynchronously lists WorkflowInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers """ - return self._properties['links'] + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - 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" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkflowPage(self._version, response, solution=self._solution) - 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): + 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, solution=self._solution) - def delete(self): + def page_with_http_info( + 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, + ) -> ApiResponse: """ - Deletes the WorkflowInstance + Retrieve a single page with response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :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: ApiResponse with WorkflowPage, status code, and headers """ - return self._proxy.delete() + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WorkflowPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with WorkflowPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WorkflowPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> WorkflowPage: """ - Access the statistics + 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 = self._version.domain.twilio.request("GET", target_url) + return WorkflowPage(self._version, response, solution=self._solution) - @property - def real_time_statistics(self): + async def get_page_async(self, target_url: str) -> WorkflowPage: """ - Access the real_time_statistics + Asynchronously retrieve a specific page of WorkflowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsList + :returns: Page of WorkflowInstance """ - return self._proxy.real_time_statistics + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkflowPage(self._version, response, solution=self._solution) - @property - def cumulative_statistics(self): + def get(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 __call__(self, sid: str) -> WorkflowContext: + """ + Constructs a WorkflowContext + + :param sid: The SID of the Workflow resource to update. + """ + return WorkflowContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..f104fd41bb 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,542 @@ -# 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.api_response import ApiResponse 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 WorkflowCumulativeStatisticsList(ListResource): - """ """ +class WorkflowCumulativeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. + :ivar avg_task_acceptance_time: The average time in seconds between Task creation and acceptance. + :ivar start_time: The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar end_time: The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar reservations_created: The total number of Reservations that were created for Workers. + :ivar reservations_accepted: The total number of Reservations accepted by Workers. + :ivar reservations_rejected: The total number of Reservations that were rejected. + :ivar reservations_timed_out: The total number of Reservations that were timed out. + :ivar reservations_canceled: The total number of Reservations that were canceled. + :ivar reservations_rescinded: The total number of Reservations that were rescinded. + :ivar split_by_wait_time: A list of objects that describe the number of Tasks canceled and reservations accepted above and below the thresholds specified in seconds. + :ivar wait_duration_until_accepted: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were accepted. + :ivar wait_duration_until_canceled: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were canceled. + :ivar tasks_canceled: The total number of Tasks that were canceled. + :ivar tasks_completed: The total number of Tasks that were completed. + :ivar tasks_entered: The total number of Tasks that entered the Workflow. + :ivar tasks_deleted: The total number of Tasks that were deleted. + :ivar tasks_moved: The total number of Tasks that were moved from one queue to another. + :ivar tasks_timed_out_in_workflow: The total number of Tasks that were timed out of their Workflows (and deleted). + :ivar workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value. + :ivar workspace_sid: The SID of the Workspace that contains the Workflow. + :ivar url: The absolute URL of the Workflow statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + workflow_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.avg_task_acceptance_time: Optional[int] = deserialize.integer( + payload.get("avg_task_acceptance_time") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.reservations_created: Optional[int] = deserialize.integer( + payload.get("reservations_created") + ) + self.reservations_accepted: Optional[int] = deserialize.integer( + payload.get("reservations_accepted") + ) + self.reservations_rejected: Optional[int] = deserialize.integer( + payload.get("reservations_rejected") + ) + self.reservations_timed_out: Optional[int] = deserialize.integer( + payload.get("reservations_timed_out") + ) + self.reservations_canceled: Optional[int] = deserialize.integer( + payload.get("reservations_canceled") + ) + self.reservations_rescinded: Optional[int] = deserialize.integer( + payload.get("reservations_rescinded") + ) + self.split_by_wait_time: Optional[Dict[str, object]] = payload.get( + "split_by_wait_time" + ) + self.wait_duration_until_accepted: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_accepted" + ) + self.wait_duration_until_canceled: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_canceled" + ) + self.tasks_canceled: Optional[int] = deserialize.integer( + payload.get("tasks_canceled") + ) + self.tasks_completed: Optional[int] = deserialize.integer( + payload.get("tasks_completed") + ) + self.tasks_entered: Optional[int] = deserialize.integer( + payload.get("tasks_entered") + ) + self.tasks_deleted: Optional[int] = deserialize.integer( + payload.get("tasks_deleted") + ) + self.tasks_moved: Optional[int] = deserialize.integer( + payload.get("tasks_moved") + ) + self.tasks_timed_out_in_workflow: Optional[int] = deserialize.integer( + payload.get("tasks_timed_out_in_workflow") + ) + self.workflow_sid: Optional[str] = payload.get("workflow_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") - def __init__(self, version, workspace_sid, workflow_sid): - """ - Initialize the WorkflowCumulativeStatisticsList + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } - :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 + self._context: Optional[WorkflowCumulativeStatisticsContext] = None - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsList + @property + def _proxy(self) -> "WorkflowCumulativeStatisticsContext": """ - super(WorkflowCumulativeStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, } + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def get(self): + :returns: WorkflowCumulativeStatisticsContext for this WorkflowCumulativeStatisticsInstance """ - Constructs a 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 - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext + 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": """ - return WorkflowCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], - ) + Fetch the WorkflowCumulativeStatisticsInstance - def __call__(self): - """ - Constructs a WorkflowCumulativeStatisticsContext + :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.WorkflowCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext + :returns: The fetched WorkflowCumulativeStatisticsInstance """ - return WorkflowCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, ) - def __repr__(self): + 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": """ - Provide a friendly representation + Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance - :returns: Machine friendly representation - :rtype: str - """ - return '' + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + :returns: The fetched WorkflowCumulativeStatisticsInstance + """ + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) -class WorkflowCumulativeStatisticsPage(Page): - """ """ - - def __init__(self, version, response, solution): + def fetch_with_http_info( + 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, + ) -> ApiResponse: """ - Initialize the WorkflowCumulativeStatisticsPage + Fetch the WorkflowCumulativeStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - super(WorkflowCumulativeStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: """ - Build an instance of WorkflowCumulativeStatisticsInstance + Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WorkflowCumulativeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], + return await self._proxy.fetch_with_http_info_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: 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, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) - def fetch(self, end_date=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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, ) - + payload, _, _ = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return WorkflowCumulativeStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class WorkflowCumulativeStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid, workflow_sid): - """ - Initialize the WorkflowCumulativeStatisticsInstance - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance - """ - super(WorkflowCumulativeStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.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 - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def fetch_with_http_info( + 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, + ) -> ApiResponse: """ - return self._properties['account_sid'] + Fetch the WorkflowCumulativeStatisticsInstance and return response metadata - @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'] + :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 start_time(self): + :returns: ApiResponse with instance, status code, and headers """ - :returns: The beginning of the interval during which these statistics were calculated - :rtype: datetime - """ - return self._properties['start_time'] + payload, status_code, headers = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkflowCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) - @property - def end_time(self): - """ - :returns: The end of the interval during which these statistics were calculated - :rtype: datetime - """ - return self._properties['end_time'] + headers = values.of({}) - @property - def reservations_created(self): - """ - :returns: The total number of Reservations that were created for Workers - :rtype: unicode - """ - return self._properties['reservations_created'] + headers["Accept"] = "application/json" - @property - def reservations_accepted(self): - """ - :returns: The total number of Reservations accepted by Workers - :rtype: unicode - """ - return self._properties['reservations_accepted'] + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - @property - def reservations_rejected(self): - """ - :returns: The total number of Reservations that were rejected - :rtype: unicode + 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: """ - return self._properties['reservations_rejected'] + Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance - @property - def reservations_timed_out(self): - """ - :returns: The total number of Reservations that were timed out - :rtype: unicode - """ - return self._properties['reservations_timed_out'] + :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_canceled(self): - """ - :returns: The total number of Reservations that were canceled - :rtype: unicode + :returns: The fetched WorkflowCumulativeStatisticsInstance """ - return self._properties['reservations_canceled'] + payload, _, _ = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + return WorkflowCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) - @property - def reservations_rescinded(self): + async def fetch_with_http_info_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, + ) -> ApiResponse: """ - :returns: The total number of Reservations that were rescinded - :rtype: unicode - """ - return self._properties['reservations_rescinded'] + Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance and return response metadata - @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'] + :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 wait_duration_until_accepted(self): + :returns: ApiResponse with instance, status code, and headers """ - :returns: The wait duration statistics for Tasks that were accepted - :rtype: dict - """ - return self._properties['wait_duration_until_accepted'] + payload, status_code, headers = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkflowCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @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): + def get(self) -> WorkflowCumulativeStatisticsContext: """ - :returns: The SID of the Workspace that contains the Workflow. - :rtype: unicode - """ - 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..944dac550d 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,359 @@ -# 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.api_response import ApiResponse 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 WorkflowRealTimeStatisticsList(ListResource): - """ """ +class WorkflowRealTimeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. + :ivar longest_task_waiting_age: The age of the longest waiting Task. + :ivar longest_task_waiting_sid: The SID of the longest waiting Task. + :ivar tasks_by_priority: The number of Tasks by priority. For example: `{\"0\": \"10\", \"99\": \"5\"}` shows 10 Tasks at priority 0 and 5 at priority 99. + :ivar tasks_by_status: The number of Tasks by their current status. For example: `{\"pending\": \"1\", \"reserved\": \"3\", \"assigned\": \"2\", \"completed\": \"5\"}`. + :ivar total_tasks: The total number of Tasks. + :ivar workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. + :ivar workspace_sid: The SID of the Workspace that contains the Workflow. + :ivar url: The absolute URL of the Workflow statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + workflow_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.longest_task_waiting_age: Optional[int] = deserialize.integer( + payload.get("longest_task_waiting_age") + ) + self.longest_task_waiting_sid: Optional[str] = payload.get( + "longest_task_waiting_sid" + ) + self.tasks_by_priority: Optional[Dict[str, object]] = payload.get( + "tasks_by_priority" + ) + self.tasks_by_status: Optional[Dict[str, object]] = payload.get( + "tasks_by_status" + ) + self.total_tasks: Optional[int] = deserialize.integer( + payload.get("total_tasks") + ) + self.workflow_sid: Optional[str] = payload.get("workflow_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") - def __init__(self, version, workspace_sid, workflow_sid): - """ - Initialize the WorkflowRealTimeStatisticsList + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } - :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 + self._context: Optional[WorkflowRealTimeStatisticsContext] = None - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsList + @property + def _proxy(self) -> "WorkflowRealTimeStatisticsContext": """ - super(WorkflowRealTimeStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, } + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def get(self): + :returns: WorkflowRealTimeStatisticsContext for this WorkflowRealTimeStatisticsInstance """ - Constructs a 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 - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkflowRealTimeStatisticsInstance": """ - return WorkflowRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], - ) + Fetch the WorkflowRealTimeStatisticsInstance - def __call__(self): - """ - Constructs a WorkflowRealTimeStatisticsContext + :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.WorkflowRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext + :returns: The fetched WorkflowRealTimeStatisticsInstance """ - return WorkflowRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], + return self._proxy.fetch( + task_channel=task_channel, ) - def __repr__(self): + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkflowRealTimeStatisticsInstance": """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' + Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. -class WorkflowRealTimeStatisticsPage(Page): - """ """ + :returns: The fetched WorkflowRealTimeStatisticsInstance + """ + return await self._proxy.fetch_async( + task_channel=task_channel, + ) - def __init__(self, version, response, solution): + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: """ - Initialize the WorkflowRealTimeStatisticsPage + Fetch the WorkflowRealTimeStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - super(WorkflowRealTimeStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info( + task_channel=task_channel, + ) - def get_instance(self, payload): + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: """ - Build an instance of WorkflowRealTimeStatisticsInstance + Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WorkflowRealTimeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], + return await self._proxy.fetch_with_http_info_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) -> tuple: """ - Fetch the WorkflowRealTimeStatisticsInstance + Internal helper for fetch operation - :param unicode task_channel: Only calculate real-time statistics on this TaskChannel + Returns: + tuple: (payload, status_code, headers) + """ - :returns: The fetched WorkflowRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance + params = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> WorkflowRealTimeStatisticsInstance: """ - data = values.of({'TaskChannel': task_channel, }) + Fetch the WorkflowRealTimeStatisticsInstance - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + :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 + """ + payload, _, _ = self._fetch(task_channel=task_channel) 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): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Fetch the WorkflowRealTimeStatisticsInstance and return response metadata + :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`. -class WorkflowRealTimeStatisticsInstance(InstanceResource): - """ """ + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(task_channel=task_channel) + instance = WorkflowRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __init__(self, version, payload, workspace_sid, workflow_sid): + async def _fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> tuple: """ - Initialize the WorkflowRealTimeStatisticsInstance + Internal async helper for fetch operation - :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: + tuple: (payload, status_code, headers) """ - 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'), - } + params = values.of( + { + "TaskChannel": task_channel, + } + ) - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_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: 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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - @property - def account_sid(self): + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> WorkflowRealTimeStatisticsInstance: """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance - @property - def longest_task_waiting_age(self): - """ - :returns: The age of the longest waiting Task - :rtype: unicode - """ - return self._properties['longest_task_waiting_age'] + :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`. - @property - def longest_task_waiting_sid(self): - """ - :returns: The SID of the longest waiting Task - :rtype: unicode + :returns: The fetched WorkflowRealTimeStatisticsInstance """ - return self._properties['longest_task_waiting_sid'] + payload, _, _ = await self._fetch_async(task_channel=task_channel) + return WorkflowRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) - @property - def tasks_by_priority(self): - """ - :returns: The number of Tasks by priority - :rtype: dict + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: """ - return self._properties['tasks_by_priority'] + Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance and return response metadata - @property - def tasks_by_status(self): - """ - :returns: The number of Tasks by their current status - :rtype: dict - """ - return self._properties['tasks_by_status'] + :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`. - @property - def total_tasks(self): + :returns: ApiResponse with instance, status code, and headers """ - :returns: The total number of Tasks - :rtype: unicode - """ - return self._properties['total_tasks'] + payload, status_code, headers = await self._fetch_async( + task_channel=task_channel + ) + instance = WorkflowRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @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 + def __repr__(self) -> str: """ - return self._properties['workflow_sid'] + Provide a friendly representation - @property - def workspace_sid(self): + :returns: Machine friendly representation """ - :returns: The SID of the Workspace that contains the Workflow. - :rtype: unicode + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class WorkflowRealTimeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ - return self._properties['workspace_sid'] + Initialize the WorkflowRealTimeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to fetch. + :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. - @property - def url(self): """ - :returns: The absolute URL of the Workflow statistics resource - :rtype: unicode + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + + def get(self) -> WorkflowRealTimeStatisticsContext: """ - return self._properties['url'] + Constructs a WorkflowRealTimeStatisticsContext - def fetch(self, task_channel=values.unset): """ - Fetch the WorkflowRealTimeStatisticsInstance + return WorkflowRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) - :param unicode task_channel: Only calculate real-time statistics on this TaskChannel + def __call__(self) -> WorkflowRealTimeStatisticsContext: + """ + 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..1aa812c61d 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py @@ -1,303 +1,472 @@ -# 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.api_response import ApiResponse 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): - """ """ - def __init__(self, version, workspace_sid, workflow_sid): - """ - Initialize the WorkflowStatisticsList +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, + } - :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 + self._context: Optional[WorkflowStatisticsContext] = None - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsList + @property + def _proxy(self) -> "WorkflowStatisticsContext": """ - super(WorkflowStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, } + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def get(self): + :returns: WorkflowStatisticsContext for this WorkflowStatisticsInstance """ - Constructs a WorkflowStatisticsContext + if self._context is None: + self._context = WorkflowStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return self._context - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkflowStatisticsInstance": """ - return WorkflowStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], - ) + Fetch the WorkflowStatisticsInstance - def __call__(self): - """ - Constructs a WorkflowStatisticsContext + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext + :returns: The fetched WorkflowStatisticsInstance """ - return WorkflowStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], + return self._proxy.fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + 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": """ - return '' + 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. -class WorkflowStatisticsPage(Page): - """ """ + :returns: The fetched WorkflowStatisticsInstance + """ + return await self._proxy.fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) - def __init__(self, version, response, solution): + def fetch_with_http_info( + 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, + ) -> ApiResponse: """ - Initialize the WorkflowStatisticsPage + Fetch the WorkflowStatisticsInstance with HTTP info - :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 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.WorkflowStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsPage + :returns: ApiResponse with instance, status code, and headers """ - super(WorkflowStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) - def get_instance(self, payload): + async def fetch_with_http_info_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, + ) -> ApiResponse: """ - Build an instance of WorkflowStatisticsInstance + Asynchronous coroutine to fetch the WorkflowStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WorkflowStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], + return await self._proxy.fetch_with_http_info_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class WorkflowStatisticsContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid, workflow_sid): + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ Initialize the WorkflowStatisticsContext - :param Version version: Version that contains the resource - :param workspace_sid: The 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_statistics.WorkflowStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to fetch. + :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. """ - super(WorkflowStatisticsContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, } - self._uri = '/Workspaces/{workspace_sid}/Workflows/{workflow_sid}/Statistics'.format(**self._solution) + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Workflows/{workflow_sid}/Statistics".format( + **self._solution + ) + ) + + def _fetch( + self, + minutes: 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, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) - def fetch(self, minutes=values.unset, start_date=values.unset, - end_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkflowStatisticsInstance: """ Fetch the WorkflowStatisticsInstance - :param 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 + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. :returns: The fetched WorkflowStatisticsInstance - :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, - }) - - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) - + payload, _, _ = self._fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) 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 fetch_with_http_info( + 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, + ) -> ApiResponse: """ - Provide a friendly representation + Fetch the WorkflowStatisticsInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + :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: ApiResponse with instance, status code, and headers """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + payload, status_code, headers = self._fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkflowStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + headers = values.of({}) -class WorkflowStatisticsInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, payload, workspace_sid, workflow_sid): - """ - Initialize the WorkflowStatisticsInstance + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsInstance + 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: """ - super(WorkflowStatisticsInstance, self).__init__(version) + Asynchronous coroutine to fetch the WorkflowStatisticsInstance - # 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'), - } + :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. - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, } - - @property - def _proxy(self): + :returns: The fetched WorkflowStatisticsInstance """ - 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._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + return WorkflowStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) - :returns: WorkflowStatisticsContext for this WorkflowStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext + async def fetch_with_http_info_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, + ) -> ApiResponse: """ - 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 + Asynchronous coroutine to fetch the WorkflowStatisticsInstance and return response metadata - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_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 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. - @property - def cumulative(self): - """ - :returns: An object that contains the cumulative statistics for the Workflow - :rtype: dict + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['cumulative'] + payload, status_code, headers = await self._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkflowStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def realtime(self): - """ - :returns: An object that contains the real-time statistics for the Workflow - :rtype: dict + def __repr__(self) -> str: """ - return self._properties['realtime'] + Provide a friendly representation - @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 + :returns: Machine friendly representation """ - return self._properties['workflow_sid'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace that contains the Workflow - :rtype: unicode + +class WorkflowStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ - return self._properties['workspace_sid'] + Initialize the WorkflowStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to fetch. + :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. - @property - def url(self): """ - :returns: The absolute URL of the Workflow statistics resource - :rtype: unicode + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + + def get(self) -> WorkflowStatisticsContext: """ - return self._properties['url'] + Constructs a WorkflowStatisticsContext - def fetch(self, minutes=values.unset, start_date=values.unset, - end_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): """ - Fetch the WorkflowStatisticsInstance + return WorkflowStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) - :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 + def __call__(self) -> WorkflowStatisticsContext: + """ + 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..8d7262cdb0 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py @@ -1,431 +1,520 @@ -# 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.api_response import ApiResponse 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): - """ """ +class WorkspaceCumulativeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. + :ivar avg_task_acceptance_time: The average time in seconds between Task creation and acceptance. + :ivar start_time: The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar end_time: The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar reservations_created: The total number of Reservations that were created for Workers. + :ivar reservations_accepted: The total number of Reservations accepted by Workers. + :ivar reservations_rejected: The total number of Reservations that were rejected. + :ivar reservations_timed_out: The total number of Reservations that were timed out. + :ivar reservations_canceled: The total number of Reservations that were canceled. + :ivar reservations_rescinded: The total number of Reservations that were rescinded. + :ivar split_by_wait_time: A list of objects that describe the number of Tasks canceled and reservations accepted above and below the thresholds specified in seconds. + :ivar wait_duration_until_accepted: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were accepted. + :ivar wait_duration_until_canceled: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were canceled. + :ivar tasks_canceled: The total number of Tasks that were canceled. + :ivar tasks_completed: The total number of Tasks that were completed. + :ivar tasks_created: The total number of Tasks created. + :ivar tasks_deleted: The total number of Tasks that were deleted. + :ivar tasks_moved: The total number of Tasks that were moved from one queue to another. + :ivar tasks_timed_out_in_workflow: The total number of Tasks that were timed out of their Workflows (and deleted). + :ivar workspace_sid: The SID of the Workspace. + :ivar url: The absolute URL of the Workspace statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.avg_task_acceptance_time: Optional[int] = deserialize.integer( + payload.get("avg_task_acceptance_time") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.reservations_created: Optional[int] = deserialize.integer( + payload.get("reservations_created") + ) + self.reservations_accepted: Optional[int] = deserialize.integer( + payload.get("reservations_accepted") + ) + self.reservations_rejected: Optional[int] = deserialize.integer( + payload.get("reservations_rejected") + ) + self.reservations_timed_out: Optional[int] = deserialize.integer( + payload.get("reservations_timed_out") + ) + self.reservations_canceled: Optional[int] = deserialize.integer( + payload.get("reservations_canceled") + ) + self.reservations_rescinded: Optional[int] = deserialize.integer( + payload.get("reservations_rescinded") + ) + self.split_by_wait_time: Optional[Dict[str, object]] = payload.get( + "split_by_wait_time" + ) + self.wait_duration_until_accepted: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_accepted" + ) + self.wait_duration_until_canceled: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_canceled" + ) + self.tasks_canceled: Optional[int] = deserialize.integer( + payload.get("tasks_canceled") + ) + self.tasks_completed: Optional[int] = deserialize.integer( + payload.get("tasks_completed") + ) + self.tasks_created: Optional[int] = deserialize.integer( + payload.get("tasks_created") + ) + self.tasks_deleted: Optional[int] = deserialize.integer( + payload.get("tasks_deleted") + ) + self.tasks_moved: Optional[int] = deserialize.integer( + payload.get("tasks_moved") + ) + self.tasks_timed_out_in_workflow: Optional[int] = deserialize.integer( + payload.get("tasks_timed_out_in_workflow") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") - def __init__(self, version, workspace_sid): - """ - Initialize the WorkspaceCumulativeStatisticsList + self._solution = { + "workspace_sid": workspace_sid, + } - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace + self._context: Optional[WorkspaceCumulativeStatisticsContext] = None - :returns: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsList + @property + def _proxy(self) -> "WorkspaceCumulativeStatisticsContext": """ - super(WorkspaceCumulativeStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def get(self): + :returns: WorkspaceCumulativeStatisticsContext for this WorkspaceCumulativeStatisticsInstance """ - Constructs a WorkspaceCumulativeStatisticsContext + if self._context is None: + self._context = WorkspaceCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context - :returns: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsContext + 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": """ - return WorkspaceCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) + Fetch the WorkspaceCumulativeStatisticsInstance - def __call__(self): - """ - Constructs a WorkspaceCumulativeStatisticsContext + :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.WorkspaceCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsContext + :returns: The fetched WorkspaceCumulativeStatisticsInstance """ - return WorkspaceCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, ) - def __repr__(self): + 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": """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' + Asynchronous coroutine to fetch the WorkspaceCumulativeStatisticsInstance + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. -class WorkspaceCumulativeStatisticsPage(Page): - """ """ + :returns: The fetched WorkspaceCumulativeStatisticsInstance + """ + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) - def __init__(self, version, response, solution): + def fetch_with_http_info( + 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, + ) -> ApiResponse: """ - Initialize the WorkspaceCumulativeStatisticsPage + Fetch the WorkspaceCumulativeStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - super(WorkspaceCumulativeStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: """ - Build an instance of WorkspaceCumulativeStatisticsInstance + Asynchronous coroutine to fetch the WorkspaceCumulativeStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WorkspaceCumulativeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], + return await self._proxy.fetch_with_http_info_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, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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, ) - + payload, _, _ = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return WorkspaceCumulativeStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], + workspace_sid=self._solution["workspace_sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class WorkspaceCumulativeStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid): - """ - Initialize the WorkspaceCumulativeStatisticsInstance - - :returns: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsInstance - """ - super(WorkspaceCumulativeStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.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 - - :returns: WorkspaceCumulativeStatisticsContext for this WorkspaceCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsContext + def fetch_with_http_info( + 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, + ) -> ApiResponse: """ - if self._context is None: - self._context = WorkspaceCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._context + Fetch the WorkspaceCumulativeStatisticsInstance and return response metadata - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. - @property - def avg_task_acceptance_time(self): + :returns: ApiResponse with instance, status code, and headers """ - :returns: The average time in seconds between Task creation and acceptance - :rtype: unicode - """ - return self._properties['avg_task_acceptance_time'] + payload, status_code, headers = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkspaceCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) - @property - def start_time(self): - """ - :returns: The beginning of the interval during which these statistics were calculated - :rtype: datetime - """ - return self._properties['start_time'] + headers = values.of({}) - @property - def end_time(self): - """ - :returns: The end of the interval during which these statistics were calculated - :rtype: datetime - """ - return self._properties['end_time'] + headers["Accept"] = "application/json" - @property - def reservations_created(self): - """ - :returns: The total number of Reservations that were created for Workers - :rtype: unicode - """ - return self._properties['reservations_created'] + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - @property - def reservations_accepted(self): - """ - :returns: The total number of Reservations accepted by Workers - :rtype: unicode + 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['reservations_accepted'] + Asynchronous coroutine to fetch the WorkspaceCumulativeStatisticsInstance - @property - def reservations_rejected(self): - """ - :returns: The total number of Reservations that were rejected - :rtype: unicode - """ - return self._properties['reservations_rejected'] + :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_timed_out(self): - """ - :returns: The total number of Reservations that were timed out - :rtype: unicode + :returns: The fetched WorkspaceCumulativeStatisticsInstance """ - return self._properties['reservations_timed_out'] + payload, _, _ = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + return WorkspaceCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) - @property - def reservations_canceled(self): + async def fetch_with_http_info_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, + ) -> ApiResponse: """ - :returns: The total number of Reservations that were canceled - :rtype: unicode - """ - return self._properties['reservations_canceled'] + Asynchronous coroutine to fetch the WorkspaceCumulativeStatisticsInstance and return response metadata - @property - def reservations_rescinded(self): - """ - :returns: The total number of Reservations that were rescinded - :rtype: unicode - """ - return self._properties['reservations_rescinded'] + :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 split_by_wait_time(self): + :returns: ApiResponse with instance, status code, and headers """ - :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, status_code, headers = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkspaceCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def wait_duration_until_accepted(self): + def __repr__(self) -> str: """ - :returns: The wait duration statistics for Tasks that were accepted - :rtype: dict - """ - return self._properties['wait_duration_until_accepted'] + Provide a friendly representation - @property - def wait_duration_until_canceled(self): - """ - :returns: The wait duration 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..559ec20f14 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,345 @@ -# 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.api_response import ApiResponse 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): - """ """ +class WorkspaceRealTimeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. + :ivar activity_statistics: The number of current Workers by Activity. + :ivar longest_task_waiting_age: The age of the longest waiting Task. + :ivar longest_task_waiting_sid: The SID of the longest waiting Task. + :ivar tasks_by_priority: The number of Tasks by priority. For example: `{\"0\": \"10\", \"99\": \"5\"}` shows 10 Tasks at priority 0 and 5 at priority 99. + :ivar tasks_by_status: The number of Tasks by their current status. For example: `{\"pending\": \"1\", \"reserved\": \"3\", \"assigned\": \"2\", \"completed\": \"5\"}`. + :ivar total_tasks: The total number of Tasks. + :ivar total_workers: The total number of Workers in the Workspace. + :ivar workspace_sid: The SID of the Workspace. + :ivar url: The absolute URL of the Workspace statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.activity_statistics: Optional[List[Dict[str, object]]] = payload.get( + "activity_statistics" + ) + self.longest_task_waiting_age: Optional[int] = deserialize.integer( + payload.get("longest_task_waiting_age") + ) + self.longest_task_waiting_sid: Optional[str] = payload.get( + "longest_task_waiting_sid" + ) + self.tasks_by_priority: Optional[Dict[str, object]] = payload.get( + "tasks_by_priority" + ) + self.tasks_by_status: Optional[Dict[str, object]] = payload.get( + "tasks_by_status" + ) + self.total_tasks: Optional[int] = deserialize.integer( + payload.get("total_tasks") + ) + self.total_workers: Optional[int] = deserialize.integer( + payload.get("total_workers") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") - def __init__(self, version, workspace_sid): - """ - Initialize the WorkspaceRealTimeStatisticsList + self._solution = { + "workspace_sid": workspace_sid, + } - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace + self._context: Optional[WorkspaceRealTimeStatisticsContext] = None - :returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsList + @property + def _proxy(self) -> "WorkspaceRealTimeStatisticsContext": """ - super(WorkspaceRealTimeStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def get(self): + :returns: WorkspaceRealTimeStatisticsContext for this WorkspaceRealTimeStatisticsInstance """ - Constructs a WorkspaceRealTimeStatisticsContext + if self._context is None: + self._context = WorkspaceRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context - :returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsContext + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkspaceRealTimeStatisticsInstance": """ - return WorkspaceRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) + Fetch the WorkspaceRealTimeStatisticsInstance - def __call__(self): - """ - Constructs a WorkspaceRealTimeStatisticsContext + :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.WorkspaceRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsContext + :returns: The fetched WorkspaceRealTimeStatisticsInstance """ - return WorkspaceRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], + return self._proxy.fetch( + task_channel=task_channel, ) - 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 - """ - return '' + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :returns: The fetched WorkspaceRealTimeStatisticsInstance + """ + return await self._proxy.fetch_async( + task_channel=task_channel, + ) -class WorkspaceRealTimeStatisticsPage(Page): - """ """ - - def __init__(self, version, response, solution): + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: """ - Initialize the WorkspaceRealTimeStatisticsPage + Fetch the WorkspaceRealTimeStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - super(WorkspaceRealTimeStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info( + task_channel=task_channel, + ) - def get_instance(self, payload): + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: """ - Build an instance of WorkspaceRealTimeStatisticsInstance + Asynchronous coroutine to fetch the WorkspaceRealTimeStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WorkspaceRealTimeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], + return await self._proxy.fetch_with_http_info_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) -> tuple: """ - Fetch the WorkspaceRealTimeStatisticsInstance + Internal helper for fetch operation - :param unicode task_channel: Only calculate real-time statistics on this TaskChannel + Returns: + tuple: (payload, status_code, headers) + """ - :returns: The fetched WorkspaceRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance + params = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> WorkspaceRealTimeStatisticsInstance: """ - data = values.of({'TaskChannel': task_channel, }) + Fetch the WorkspaceRealTimeStatisticsInstance - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + :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 + """ + payload, _, _ = self._fetch(task_channel=task_channel) return WorkspaceRealTimeStatisticsInstance( 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 + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Fetch the WorkspaceRealTimeStatisticsInstance and return response metadata + :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`. -class WorkspaceRealTimeStatisticsInstance(InstanceResource): - """ """ + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(task_channel=task_channel) + instance = WorkspaceRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __init__(self, version, payload, workspace_sid): + async def _fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> tuple: """ - Initialize the WorkspaceRealTimeStatisticsInstance + Internal async helper for fetch operation - :returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - 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'), - } + params = 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 + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> WorkspaceRealTimeStatisticsInstance: """ - return self._properties['account_sid'] + Asynchronous coroutine to fetch the WorkspaceRealTimeStatisticsInstance - @property - def activity_statistics(self): - """ - :returns: The number of current Workers by Activity - :rtype: dict - """ - return self._properties['activity_statistics'] + :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`. - @property - def longest_task_waiting_age(self): - """ - :returns: The age of the longest waiting Task - :rtype: unicode + :returns: The fetched WorkspaceRealTimeStatisticsInstance """ - return self._properties['longest_task_waiting_age'] + payload, _, _ = await self._fetch_async(task_channel=task_channel) + return WorkspaceRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) - @property - def longest_task_waiting_sid(self): + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: """ - :returns: The SID of the longest waiting Task - :rtype: unicode - """ - return self._properties['longest_task_waiting_sid'] + Asynchronous coroutine to fetch the WorkspaceRealTimeStatisticsInstance and return response metadata - @property - def tasks_by_priority(self): - """ - :returns: The number of Tasks by priority - :rtype: dict - """ - return self._properties['tasks_by_priority'] + :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`. - @property - def tasks_by_status(self): - """ - :returns: The number of Tasks by their current status - :rtype: dict + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['tasks_by_status'] + payload, status_code, headers = await self._fetch_async( + task_channel=task_channel + ) + instance = WorkspaceRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def total_tasks(self): + def __repr__(self) -> str: """ - :returns: The total number of Tasks - :rtype: unicode - """ - return self._properties['total_tasks'] + Provide a friendly representation - @property - def total_workers(self): - """ - :returns: The total number of Workers in the Workspace - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['total_workers'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace - :rtype: unicode + +class WorkspaceRealTimeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): """ - return self._properties['workspace_sid'] + Initialize the WorkspaceRealTimeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. - @property - def url(self): """ - :returns: The absolute URL of the Workspace statistics resource - :rtype: unicode + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkspaceRealTimeStatisticsContext: """ - 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..e30fecf3e1 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py @@ -1,280 +1,446 @@ -# 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.api_response import ApiResponse 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 WorkspaceStatisticsList(ListResource): - """ """ +from twilio.base.version import Version - def __init__(self, version, workspace_sid): - """ - Initialize the WorkspaceStatisticsList - - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace - :returns: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsList - """ - super(WorkspaceStatisticsList, self).__init__(version) +class WorkspaceStatisticsInstance(InstanceResource): + """ + :ivar realtime: An object that contains the real-time statistics for the Workspace. + :ivar cumulative: An object that contains the cumulative statistics for the Workspace. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. + :ivar workspace_sid: The SID of the Workspace. + :ivar url: The absolute URL of the Workspace statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.realtime: Optional[Dict[str, object]] = payload.get("realtime") + self.cumulative: Optional[Dict[str, object]] = payload.get("cumulative") + self.account_sid: Optional[str] = payload.get("account_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + } - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } + self._context: Optional[WorkspaceStatisticsContext] = None - def get(self): + @property + def _proxy(self) -> "WorkspaceStatisticsContext": """ - Constructs a WorkspaceStatisticsContext + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsContext + :returns: WorkspaceStatisticsContext for this WorkspaceStatisticsInstance """ - return WorkspaceStatisticsContext(self._version, workspace_sid=self._solution['workspace_sid'], ) + if self._context is None: + self._context = WorkspaceStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context - def __call__(self): + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkspaceStatisticsInstance": """ - Constructs a WorkspaceStatisticsContext + Fetch the WorkspaceStatisticsInstance - :returns: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsContext - """ - return WorkspaceStatisticsContext(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_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 __repr__(self): + :returns: The fetched WorkspaceStatisticsInstance """ - Provide a friendly representation + 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: Machine friendly representation - :rtype: str + 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 '' + Asynchronous coroutine to fetch the WorkspaceStatisticsInstance + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. -class WorkspaceStatisticsPage(Page): - """ """ + :returns: The fetched WorkspaceStatisticsInstance + """ + return await self._proxy.fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) - def __init__(self, version, response, solution): + def fetch_with_http_info( + 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, + ) -> ApiResponse: """ - Initialize the WorkspaceStatisticsPage + Fetch the WorkspaceStatisticsInstance with HTTP info - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The SID of the Workspace + :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.WorkspaceStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsPage + :returns: ApiResponse with instance, status code, and headers """ - super(WorkspaceStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch_with_http_info( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) - def get_instance(self, payload): + async def fetch_with_http_info_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, + ) -> ApiResponse: """ - Build an instance of WorkspaceStatisticsInstance + Asynchronous coroutine to fetch the WorkspaceStatisticsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return WorkspaceStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], + return await self._proxy.fetch_with_http_info_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 WorkspaceStatisticsContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkspaceStatisticsContext - :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_statistics.WorkspaceStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsContext + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. """ - super(WorkspaceStatisticsContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/Statistics'.format(**self._solution) + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Statistics".format(**self._solution) + + def _fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) - def fetch(self, minutes=values.unset, start_date=values.unset, - end_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkspaceStatisticsInstance: """ Fetch the WorkspaceStatisticsInstance - :param 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 + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. :returns: The fetched WorkspaceStatisticsInstance - :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, - }) - - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) - + payload, _, _ = self._fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return WorkspaceStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], + workspace_sid=self._solution["workspace_sid"], ) - def __repr__(self): + def fetch_with_http_info( + 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, + ) -> ApiResponse: """ - Provide a friendly representation + Fetch the WorkspaceStatisticsInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + :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: ApiResponse with instance, status code, and headers """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + payload, status_code, headers = self._fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkspaceStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + headers = values.of({}) -class WorkspaceStatisticsInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, payload, workspace_sid): - """ - Initialize the WorkspaceStatisticsInstance + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) - :returns: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsInstance + 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: """ - 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'), - } + Asynchronous coroutine to fetch the WorkspaceStatisticsInstance - # Context - self._context = None - 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. - @property - def _proxy(self): + :returns: The fetched WorkspaceStatisticsInstance """ - 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._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + return WorkspaceStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) - :returns: WorkspaceStatisticsContext for this WorkspaceStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsContext + async def fetch_with_http_info_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, + ) -> ApiResponse: """ - if self._context is None: - self._context = WorkspaceStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._context + Asynchronous coroutine to fetch the WorkspaceStatisticsInstance and return response metadata - @property - def realtime(self): - """ - :returns: n object that contains the real-time statistics for the Workspace - :rtype: dict - """ - return self._properties['realtime'] + :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. - @property - def cumulative(self): + :returns: ApiResponse with instance, status code, and headers """ - :returns: An object that contains the cumulative statistics for the Workspace - :rtype: dict - """ - return self._properties['cumulative'] + payload, status_code, headers = await self._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkspaceStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @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 workspace_sid(self): + :returns: Machine friendly representation """ - :returns: The SID of the Workspace - :rtype: unicode + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkspaceStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): """ - return self._properties['workspace_sid'] + Initialize the WorkspaceStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. - @property - def url(self): """ - :returns: The absolute URL of the Workspace statistics resource - :rtype: unicode + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkspaceStatisticsContext: """ - return self._properties['url'] + Constructs a WorkspaceStatisticsContext - 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 + return WorkspaceStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) - :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 + def __call__(self) -> WorkspaceStatisticsContext: + """ + 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 8357ee187d..7697c323b6 100644 --- a/twilio/rest/trunking/v1/trunk/__init__.py +++ b/twilio/rest/trunking/v1/trunk/__init__.py @@ -1,625 +1,1544 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): + + 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 symmetric_rtp_enabled: Whether Symmetric RTP is enabled for the trunk. When Symmetric RTP is disabled, Twilio will send RTP to the destination negotiated in the SDP. Disabling Symmetric RTP is considered to be more secure and therefore recommended. See [Symmetric RTP](https://www.twilio.com/docs/sip-trunking#symmetric-rtp) for more information. + :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.symmetric_rtp_enabled: Optional[bool] = payload.get( + "symmetric_rtp_enabled" + ) + self.auth_type_set: Optional[List[str]] = payload.get("auth_type_set") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[TrunkContext] = None - def __init__(self, version): + @property + def _proxy(self) -> "TrunkContext": """ - Initialize the TrunkList + 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: TrunkContext for this TrunkInstance + """ + if self._context is None: + self._context = TrunkContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.trunking.v1.trunk.TrunkList - :rtype: twilio.rest.trunking.v1.trunk.TrunkList + def delete(self) -> bool: """ - super(TrunkList, self).__init__(version) + Deletes the TrunkInstance - # Path Solution - self._solution = {} - self._uri = '/Trunks'.format(**self._solution) - def create(self, friendly_name=values.unset, domain_name=values.unset, - disaster_recovery_url=values.unset, - disaster_recovery_method=values.unset, recording=values.unset, - secure=values.unset, cnam_lookup_enabled=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the TrunkInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrunkInstance - :returns: The created TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkInstance + + :returns: True if delete succeeds, False otherwise """ - 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, - }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrunkInstance with HTTP info - return TrunkInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrunkInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.TrunkInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "TrunkInstance": + """ + Fetch the TrunkInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched TrunkInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(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. + Asynchronous coroutine to 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 await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of TrunkInstance records from the API. - Request is executed immediately + Fetch the TrunkInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Asynchronous coroutine to fetch the TrunkInstance with HTTP info - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return TrunkPage(self._version, response, self._solution) + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() - def get_page(self, target_url): + def update( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> "TrunkInstance": """ - Retrieve a specific page of TrunkInstance records from the API. - Request is executed immediately + Update the TrunkInstance - :param str target_url: API-generated URL for the requested results page + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: - :returns: Page of TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkPage + :returns: The updated TrunkInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, ) - return TrunkPage(self._version, response, self._solution) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> "TrunkInstance": + """ + Asynchronous coroutine to update the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: - 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, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the TrunkInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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 + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TrunkInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) - :returns: twilio.rest.trunking.v1.trunk.TrunkContext - :rtype: twilio.rest.trunking.v1.trunk.TrunkContext + @property + def credentials_lists(self) -> CredentialListList: """ - return TrunkContext(self._version, sid=sid, ) + Access the credentials_lists + """ + return self._proxy.credentials_lists - def __call__(self, sid): + @property + def ip_access_control_lists(self) -> IpAccessControlListList: """ - Constructs a TrunkContext + Access the ip_access_control_lists + """ + return self._proxy.ip_access_control_lists - :param sid: The unique string that identifies the resource + @property + def origination_urls(self) -> OriginationUrlList: + """ + Access the origination_urls + """ + return self._proxy.origination_urls - :returns: twilio.rest.trunking.v1.trunk.TrunkContext - :rtype: twilio.rest.trunking.v1.trunk.TrunkContext + @property + def phone_numbers(self) -> PhoneNumberList: """ - return TrunkContext(self._version, sid=sid, ) + Access the phone_numbers + """ + return self._proxy.phone_numbers - def __repr__(self): + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + return self._proxy.recordings + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class TrunkPage(Page): - """ """ +class TrunkContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the TrunkPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the TrunkContext - :returns: twilio.rest.trunking.v1.trunk.TrunkPage - :rtype: twilio.rest.trunking.v1.trunk.TrunkPage + :param version: Version that contains the resource + :param sid: The unique string that we created to identify the OriginationUrl resource to update. """ - super(TrunkPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Trunks/{sid}".format(**self._solution) - def get_instance(self, payload): + self._credentials_lists: Optional[CredentialListList] = None + self._ip_access_control_lists: Optional[IpAccessControlListList] = None + self._origination_urls: Optional[OriginationUrlList] = None + self._phone_numbers: Optional[PhoneNumberList] = None + self._recordings: Optional[RecordingList] = None + + def _delete(self) -> tuple: """ - Build an instance of TrunkInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :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): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the TrunkInstance and return response metadata -class TrunkContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the TrunkContext - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource + headers = values.of({}) - :returns: twilio.rest.trunking.v1.trunk.TrunkContext - :rtype: twilio.rest.trunking.v1.trunk.TrunkContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(TrunkContext, self).__init__(version) + Asynchronous coroutine that deletes the TrunkInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Trunks/{sid}'.format(**self._solution) - # Dependents - self._origination_urls = None - self._credentials_lists = None - self._ip_access_control_lists = None - self._phone_numbers = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrunkInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", 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, ) + payload, _, _ = self._fetch() + return TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - return TrunkInstance(self._version, payload, sid=self._solution['sid'], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrunkInstance and return response metadata - def delete(self): + + :returns: ApiResponse with instance, status code, and headers """ - Deletes the TrunkInstance + payload, status_code, headers = self._fetch() + instance = TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TrunkInstance: + """ + Asynchronous coroutine to fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + payload, _, _ = await self._fetch_async() + return TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrunkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._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 TrunkInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the TrunkInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = TrunkInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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({}) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return TrunkInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - @property - def origination_urls(self): - """ - Access the origination_urls + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList + 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 + payload, _, _ = await self._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, + ) + return TrunkInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TrunkInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = TrunkInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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 - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + return TrunkInstance(self._version, payload) - @property - def domain_name(self): - """ - :returns: The unique address you reserve on Twilio to which you route your SIP traffic - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['domain_name'] + Provide a friendly representation - @property - def disaster_recovery_method(self): + :returns: Machine friendly representation """ - :returns: The HTTP method we use to call the disaster_recovery_url - :rtype: unicode + return "" + + +class TrunkList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['disaster_recovery_method'] + Initialize the TrunkList + + :param version: Version that contains the resource - @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 + super().__init__(version) + + self._uri = "/Trunks" + + def _create( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> tuple: """ - return self._properties['disaster_recovery_url'] + Internal helper for create operation - @property - def friendly_name(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['friendly_name'] + Create the TrunkInstance - @property - def secure(self): + :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 """ - :returns: Whether Secure Trunking is enabled for the trunk - :rtype: bool + payload, _, _ = self._create( + 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 TrunkInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the TrunkInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + 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, + ) + instance = TrunkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['secure'] + payload, _, _ = await self._create_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, + ) + return TrunkInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the TrunkInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_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, + ) + instance = TrunkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def recording(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TrunkInstance]: """ - :returns: The recording settings for the trunk - :rtype: dict + 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['recording'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def cnam_lookup_enabled(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: Whether Caller ID Name (CNAM) lookup is enabled for the trunk - :rtype: bool + 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['cnam_lookup_enabled'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def auth_type(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The types of authentication mapped to the domain - :rtype: unicode + Streams TrunkInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['auth_type'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def auth_type_set(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: Reserved - :rtype: unicode + Asynchronously streams TrunkInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['auth_type_set'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def date_created(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrunkInstance]: """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + 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['date_created'] - @property - def date_updated(self): + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrunkInstance]: """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + Asynchronously lists TrunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['date_updated'] - @property - def sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Lists TrunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def url(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The absolute URL of the resource - :rtype: unicode + Asynchronously lists TrunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['url'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, + ) -> TrunkPage: """ - :returns: The URLs of related resources - :rtype: unicode + Retrieve a single page of TrunkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrunkInstance """ - 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 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: """ - Fetch the TrunkInstance + Asynchronously retrieve a single page of TrunkInstance records from the API. + Request is executed immediately - :returns: The fetched TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkInstance + :param page_token: PageToken provided by the API + :param page_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.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 TrunkPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Deletes the TrunkInstance + Retrieve a single page with response metadata - :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: ApiResponse with TrunkPage, status code, and headers """ - return self._proxy.delete() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def update(self, friendly_name=values.unset, 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["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TrunkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Update the TrunkInstance + Asynchronously retrieve a single page with response metadata - :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 - :returns: The updated TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkInstance + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TrunkPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TrunkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 756ce27671..540c501396 100644 --- a/twilio/rest/trunking/v1/trunk/credential_list.py +++ b/twilio/rest/trunking/v1/trunk/credential_list.py @@ -1,382 +1,893 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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") - def __init__(self, version, trunk_sid): - """ - Initialize the CredentialListList + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid or self.sid, + } - :param Version version: Version that contains the resource - :param trunk_sid: The SID of the Trunk the credential list in associated with + self._context: Optional[CredentialListContext] = None - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList + @property + def _proxy(self) -> "CredentialListContext": """ - super(CredentialListList, 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}/CredentialLists'.format(**self._solution) + :returns: CredentialListContext for this CredentialListInstance + """ + if self._context is None: + self._context = CredentialListContext( + self._version, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return self._context - def create(self, credential_list_sid): + def delete(self) -> bool: """ - Create the CredentialListInstance + Deletes the CredentialListInstance - :param unicode credential_list_sid: The SID of the Credential List that you want to associate with the trunk - :returns: The created CredentialListInstance - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'CredentialListSid': credential_list_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 CredentialListInstance - return CredentialListInstance(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 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. + 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) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialListInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.delete_with_http_info() - page = self.page(page_size=limits['page_size'], ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists CredentialListInstance 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_with_http_info_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) -> "CredentialListInstance": + """ + Fetch the CredentialListInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance] + + :returns: The fetched CredentialListInstance """ - 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) -> "CredentialListInstance": """ - Retrieve a single page of CredentialListInstance records from the API. - Request is executed immediately + Asynchronous coroutine to 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.trunking.v1.trunk.credential_list.CredentialListPage + :returns: The fetched CredentialListInstance """ - 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialListInstance with HTTP info - return CredentialListPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of CredentialListInstance records from the API. - Request is executed immediately + return self._proxy.fetch_with_http_info() - :param str target_url: API-generated URL for the requested results page + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialListInstance with HTTP info - :returns: Page of CredentialListInstance - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.fetch_with_http_info_async() - return CredentialListPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a CredentialListContext + 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 CredentialListContext(InstanceContext): - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext + def __init__(self, version: Version, trunk_sid: str, sid: str): """ - return CredentialListContext(self._version, trunk_sid=self._solution['trunk_sid'], sid=sid, ) + Initialize the CredentialListContext - def __call__(self, sid): + :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. """ - Constructs a CredentialListContext + 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}/CredentialLists/{sid}".format(**self._solution) - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext + def _delete(self) -> tuple: """ - return CredentialListContext(self._version, trunk_sid=self._solution['trunk_sid'], sid=sid, ) + Internal helper for delete operation - def __repr__(self): + Returns: + tuple: (success_boolean, status_code, headers) """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return '' + Deletes the CredentialListInstance -class CredentialListPage(Page): - """ """ + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success - def __init__(self, version, response, solution): + def delete_with_http_info(self) -> ApiResponse: """ - Initialize the CredentialListPage + Deletes the CredentialListInstance and return response metadata - :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 - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListPage - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListPage + :returns: ApiResponse with success boolean, status code, and headers """ - super(CredentialListPage, self).__init__(version, response) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - # Path Solution - self._solution = solution + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation - def get_instance(self, payload): + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of CredentialListInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance - """ - return CredentialListInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], ) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __repr__(self): + 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 '' + success, _, _ = await self._delete_async() + return success + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListInstance and return response metadata -class CredentialListContext(InstanceContext): - """ """ - def __init__(self, version, trunk_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the CredentialListContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext + Returns: + tuple: (payload, status_code, headers) """ - super(CredentialListContext, self).__init__(version) - # Path Solution - self._solution = {'trunk_sid': trunk_sid, 'sid': sid, } - self._uri = '/Trunks/{trunk_sid}/CredentialLists/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialListInstance: """ Fetch the CredentialListInstance + :returns: The fetched CredentialListInstance - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return CredentialListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialListInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CredentialListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CredentialListInstance: + """ + Asynchronous coroutine to fetch the CredentialListInstance + + :returns: The fetched CredentialListInstance + """ + payload, _, _ = await self._fetch_async() return CredentialListInstance( 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the CredentialListInstance + Asynchronous coroutine to fetch the CredentialListInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = CredentialListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialListInstance(InstanceResource): - """ """ +class CredentialListPage(Page): - def __init__(self, version, payload, trunk_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> CredentialListInstance: """ - Initialize the CredentialListInstance + Build an instance of CredentialListInstance + + :param payload: Payload response from the API + """ + + return CredentialListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance + def __repr__(self) -> str: """ - super(CredentialListInstance, self).__init__(version) + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + - # 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'), +class CredentialListList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): + """ + Initialize the CredentialListList + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the credential lists. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, } + self._uri = "/Trunks/{trunk_sid}/CredentialLists".format(**self._solution) - # Context - self._context = None - self._solution = {'trunk_sid': trunk_sid, 'sid': sid or self._properties['sid'], } + def _create(self, credential_list_sid: str) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: CredentialListContext for this CredentialListInstance - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, credential_list_sid: str) -> CredentialListInstance: """ - if self._context is None: - self._context = CredentialListContext( - self._version, - trunk_sid=self._solution['trunk_sid'], - sid=self._solution['sid'], + Create the CredentialListInstance + + :param credential_list_sid: The SID of the [Credential List](https://www.twilio.com/docs/voice/sip/api/sip-credentiallist-resource) that you want to associate with the trunk. Once associated, we will authenticate access to the trunk against this list. + + :returns: The created CredentialListInstance + """ + payload, _, _ = self._create(credential_list_sid=credential_list_sid) + return CredentialListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def create_with_http_info(self, credential_list_sid: str) -> ApiResponse: + """ + Create the CredentialListInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + credential_list_sid=credential_list_sid + ) + instance = CredentialListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, credential_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, credential_list_sid: str) -> CredentialListInstance: + """ + Asynchronously create the CredentialListInstance + + :param credential_list_sid: The SID of the [Credential List](https://www.twilio.com/docs/voice/sip/api/sip-credentiallist-resource) that you want to associate with the trunk. Once associated, we will authenticate access to the trunk against this list. + + :returns: The created CredentialListInstance + """ + payload, _, _ = await self._create_async( + credential_list_sid=credential_list_sid + ) + return CredentialListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + async def create_with_http_info_async( + self, credential_list_sid: str + ) -> ApiResponse: + """ + Asynchronously create the CredentialListInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + credential_list_sid=credential_list_sid + ) + instance = CredentialListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialListInstance]: + """ + Streams CredentialListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialListInstance]: + """ + Asynchronously streams CredentialListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialListInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialListInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: + """ + Lists CredentialListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def account_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: """ - :returns: The SID of the Account that created the resource - :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['account_sid'] - @property - def sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Lists CredentialListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def trunk_sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Trunk the credential list in associated with - :rtype: unicode + Asynchronously lists CredentialListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['trunk_sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialListPage: + """ + Asynchronously retrieve a single page of CredentialListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialListInstance """ - :returns: The RFC 2822 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialListPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_created'] + Retrieve a single page with response metadata - @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: ApiResponse with CredentialListPage, status code, and headers """ - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with CredentialListPage, status code, and headers """ - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> CredentialListPage: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of CredentialListInstance """ - Fetch the CredentialListInstance + response = self._version.domain.twilio.request("GET", target_url) + return CredentialListPage(self._version, response, solution=self._solution) - :returns: The fetched CredentialListInstance - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance + async def get_page_async(self, target_url: str) -> CredentialListPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of CredentialListInstance 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 CredentialListInstance """ - Deletes the CredentialListInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialListPage(self._version, response, solution=self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> CredentialListContext: """ - return self._proxy.delete() + Constructs a CredentialListContext + + :param sid: The unique string that we created to identify the CredentialList resource to fetch. + """ + return CredentialListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __call__(self, sid: str) -> CredentialListContext: + """ + Constructs a CredentialListContext + + :param sid: The unique string that we created to identify the CredentialList resource to fetch. + """ + return CredentialListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 4f365db720..49c56e5cbc 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,899 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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") - def __init__(self, version, trunk_sid): + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid or self.sid, + } + + self._context: Optional[IpAccessControlListContext] = None + + @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 + return self._proxy.delete() - :param unicode ip_access_control_list_sid: The SID of the IP Access Control List that you want to associate with the trunk + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance - :returns: The created IpAccessControlListInstance - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({'IpAccessControlListSid': ip_access_control_list_sid, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAccessControlListInstance with HTTP info - return IpAccessControlListInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "IpAccessControlListInstance": + """ + Fetch the IpAccessControlListInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched IpAccessControlListInstance """ - Lists IpAccessControlListInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return self._proxy.fetch() + + async def fetch_async(self) -> "IpAccessControlListInstance": + """ + Asynchronous coroutine to 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.trunking.v1.trunk.ip_access_control_list.IpAccessControlListInstance] + :returns: The fetched IpAccessControlListInstance """ - 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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of IpAccessControlListInstance records from the API. - Request is executed immediately + Fetch the IpAccessControlListInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance with HTTP info - return IpAccessControlListPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of IpAccessControlListInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of IpAccessControlListInstance - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListPage + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IpAccessControlListContext(InstanceContext): + + def __init__(self, version: Version, trunk_sid: str, sid: str): """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + Initialize the IpAccessControlListContext + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to fetch the IP Access Control List. + :param sid: The unique string that we created to identify the IpAccessControlList resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid, + } + self._uri = "/Trunks/{trunk_sid}/IpAccessControlLists/{sid}".format( + **self._solution ) - return IpAccessControlListPage(self._version, response, self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation - def get(self, sid): + Returns: + tuple: (success_boolean, status_code, headers) """ - Constructs a IpAccessControlListContext - :param sid: The unique string that identifies the resource + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the IpAccessControlListInstance - :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, ) + success, _, _ = self._delete() + return success - def __call__(self, sid): + def delete_with_http_info(self) -> ApiResponse: """ - Constructs a IpAccessControlListContext + Deletes the IpAccessControlListInstance and return response metadata - :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: ApiResponse with success boolean, status code, and headers """ - return IpAccessControlListContext(self._version, trunk_sid=self._solution['trunk_sid'], sid=sid, ) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __repr__(self): + async def _delete_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for delete operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (success_boolean, status_code, headers) """ - return '' + headers = values.of({}) -class IpAccessControlListPage(Page): - """ """ + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the IpAccessControlListPage + Asynchronous coroutine that deletes the IpAccessControlListInstance - :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 - :returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListPage - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListPage + :returns: True if delete succeeds, False otherwise """ - super(IpAccessControlListPage, self).__init__(version, response) + success, _, _ = await self._delete_async() + return success - # Path Solution - self._solution = solution + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance and return response metadata - def get_instance(self, payload): + + :returns: ApiResponse with success boolean, status code, and headers """ - Build an instance of IpAccessControlListInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :param dict payload: Payload response from the API + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListInstance - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListInstance + Returns: + tuple: (payload, status_code, headers) """ - return IpAccessControlListInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], ) - def __repr__(self): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAccessControlListInstance: """ - Provide a friendly representation + Fetch the IpAccessControlListInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched IpAccessControlListInstance """ - return '' + payload, _, _ = self._fetch() + return IpAccessControlListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAccessControlListInstance and return response metadata -class IpAccessControlListContext(InstanceContext): - """ """ - def __init__(self, version, trunk_sid, sid): + :returns: ApiResponse with instance, status code, and headers """ - Initialize the IpAccessControlListContext + payload, status_code, headers = self._fetch() + instance = IpAccessControlListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :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 + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListContext - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListContext + Returns: + tuple: (payload, status_code, headers) """ - super(IpAccessControlListContext, self).__init__(version) - # Path Solution - self._solution = {'trunk_sid': trunk_sid, 'sid': sid, } - self._uri = '/Trunks/{trunk_sid}/IpAccessControlLists/{sid}'.format(**self._solution) + headers = values.of({}) - def fetch(self): + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> IpAccessControlListInstance: """ - Fetch the IpAccessControlListInstance + Asynchronous coroutine to fetch the IpAccessControlListInstance + :returns: The fetched IpAccessControlListInstance - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - + payload, _, _ = await self._fetch_async() return IpAccessControlListInstance( 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the IpAccessControlListInstance + Asynchronous coroutine to fetch the IpAccessControlListInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = IpAccessControlListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class IpAccessControlListInstance(InstanceResource): - """ """ +class IpAccessControlListPage(Page): - def __init__(self, version, payload, trunk_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> IpAccessControlListInstance: """ - Initialize the IpAccessControlListInstance + Build an instance of IpAccessControlListInstance - :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 """ - super(IpAccessControlListInstance, self).__init__(version) - # 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'), + return IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class IpAccessControlListList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): + """ + Initialize the IpAccessControlListList + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the IP Access Control Lists. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, } + self._uri = "/Trunks/{trunk_sid}/IpAccessControlLists".format(**self._solution) - # Context - self._context = None - self._solution = {'trunk_sid': trunk_sid, 'sid': sid or self._properties['sid'], } + def _create(self, ip_access_control_list_sid: str) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: IpAccessControlListContext for this IpAccessControlListInstance - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, ip_access_control_list_sid: str) -> IpAccessControlListInstance: """ - if self._context is None: - self._context = IpAccessControlListContext( - self._version, - trunk_sid=self._solution['trunk_sid'], - sid=self._solution['sid'], + Create the IpAccessControlListInstance + + :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. + + :returns: The created IpAccessControlListInstance + """ + payload, _, _ = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) + return IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def create_with_http_info(self, ip_access_control_list_sid: str) -> ApiResponse: + """ + Create the IpAccessControlListInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, ip_access_control_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, ip_access_control_list_sid: str + ) -> IpAccessControlListInstance: + """ + Asynchronously create the IpAccessControlListInstance + + :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. + + :returns: The created IpAccessControlListInstance + """ + payload, _, _ = await self._create_async( + ip_access_control_list_sid=ip_access_control_list_sid + ) + return IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + async def create_with_http_info_async( + self, ip_access_control_list_sid: str + ) -> ApiResponse: + """ + Asynchronously create the IpAccessControlListInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpAccessControlListInstance]: + """ + Streams IpAccessControlListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAccessControlListInstance]: + """ + Asynchronously streams IpAccessControlListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams IpAccessControlListInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams IpAccessControlListInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: + """ + Lists IpAccessControlListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def account_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: """ - :returns: The SID of the Account that created the resource - :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['account_sid'] - @property - def sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Lists IpAccessControlListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def trunk_sid(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Trunk the resource is associated with - :rtype: unicode + Asynchronously lists IpAccessControlListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['trunk_sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @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, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAccessControlListPage: + """ + Asynchronously retrieve a single page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAccessControlListInstance """ - :returns: The RFC 2822 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAccessControlListPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_created'] + Retrieve a single page with response metadata - @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: ApiResponse with IpAccessControlListPage, status code, and headers """ - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IpAccessControlListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with IpAccessControlListPage, status code, and headers """ - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IpAccessControlListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> IpAccessControlListPage: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of IpAccessControlListInstance """ - Fetch the IpAccessControlListInstance + response = self._version.domain.twilio.request("GET", target_url) + return IpAccessControlListPage(self._version, response, solution=self._solution) - :returns: The fetched IpAccessControlListInstance - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListInstance + async def get_page_async(self, target_url: str) -> IpAccessControlListPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of IpAccessControlListInstance 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 IpAccessControlListInstance """ - Deletes the IpAccessControlListInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpAccessControlListPage(self._version, response, solution=self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> IpAccessControlListContext: """ - return self._proxy.delete() + Constructs a IpAccessControlListContext + + :param sid: The unique string that we created to identify the IpAccessControlList resource to fetch. + """ + return IpAccessControlListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __call__(self, sid: str) -> IpAccessControlListContext: + """ + Constructs a IpAccessControlListContext + + :param sid: The unique string that we created to identify the IpAccessControlList resource to fetch. + """ + return IpAccessControlListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 4b681e5bdb..4ac87498f8 100644 --- a/twilio/rest/trunking/v1/trunk/origination_url.py +++ b/twilio/rest/trunking/v1/trunk/origination_url.py @@ -1,483 +1,1293 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +class OriginationUrlInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the OriginationUrl resource. + :ivar sid: The unique string that we created to identify the OriginationUrl resource. + :ivar trunk_sid: The SID of the Trunk that owns the Origination URL. + :ivar weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :ivar enabled: Whether the URL is enabled. The default is `true`. + :ivar sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trunk_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.weight: Optional[int] = deserialize.integer(payload.get("weight")) + self.enabled: Optional[bool] = payload.get("enabled") + self.sip_url: Optional[str] = payload.get("sip_url") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.priority: Optional[int] = deserialize.integer(payload.get("priority")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid or self.sid, + } + + self._context: Optional[OriginationUrlContext] = None - def __init__(self, version, trunk_sid): + @property + def _proxy(self) -> "OriginationUrlContext": """ - Initialize the OriginationUrlList + 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 that owns the Origination URL + :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 - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList + def delete(self) -> bool: """ - super(OriginationUrlList, self).__init__(version) + Deletes the OriginationUrlInstance - # Path Solution - self._solution = {'trunk_sid': trunk_sid, } - self._uri = '/Trunks/{trunk_sid}/OriginationUrls'.format(**self._solution) - def create(self, weight, priority, enabled, friendly_name, sip_url): + :returns: True if delete succeeds, False otherwise """ - Create the OriginationUrlInstance + return self._proxy.delete() - :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 + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OriginationUrlInstance - :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 await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OriginationUrlInstance with HTTP info - return OriginationUrlInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Streams OriginationUrlInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OriginationUrlInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "OriginationUrlInstance": + """ + Fetch the OriginationUrlInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "OriginationUrlInstance": + """ + Asynchronous coroutine to fetch the OriginationUrlInstance - :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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of OriginationUrlInstance records from the API. - Request is executed immediately + Fetch the OriginationUrlInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlPage + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OriginationUrlInstance with HTTP info - return OriginationUrlPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of OriginationUrlInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> "OriginationUrlInstance": + """ + Update the OriginationUrlInstance - :param 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 self._proxy.update( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, ) - return OriginationUrlPage(self._version, response, self._solution) + async def update_async( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> "OriginationUrlInstance": + """ + Asynchronous coroutine to update the OriginationUrlInstance - def get(self, sid): + :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 """ - Constructs a OriginationUrlContext + return await self._proxy.update_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the OriginationUrlInstance with HTTP info - :param sid: The unique string that identifies the resource + :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: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext + :returns: ApiResponse with instance, status code, and headers """ - return OriginationUrlContext(self._version, trunk_sid=self._solution['trunk_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) - def __call__(self, sid): + async def update_with_http_info_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, + ) -> ApiResponse: """ - Constructs a OriginationUrlContext + Asynchronous coroutine to update the OriginationUrlInstance with HTTP info - :param sid: The unique string that identifies the resource + :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: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext + :returns: ApiResponse with instance, status code, and headers """ - return OriginationUrlContext(self._version, trunk_sid=self._solution['trunk_sid'], sid=sid, ) + return await self._proxy.update_with_http_info_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) - 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 OriginationUrlPage(Page): - """ """ +class OriginationUrlContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, trunk_sid: str, sid: str): """ - Initialize the OriginationUrlPage - - :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 + Initialize the OriginationUrlContext - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlPage - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlPage + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to update the OriginationUrl. + :param sid: The unique string that we created to identify the OriginationUrl resource to update. """ - super(OriginationUrlPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid, + } + self._uri = "/Trunks/{trunk_sid}/OriginationUrls/{sid}".format(**self._solution) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of OriginationUrlInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return OriginationUrlInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], ) + Deletes the OriginationUrlInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the OriginationUrlInstance and return response metadata -class OriginationUrlContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, trunk_sid, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the OriginationUrlContext - :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 + headers = values.of({}) - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(OriginationUrlContext, self).__init__(version) + Asynchronous coroutine that deletes the OriginationUrlInstance - # Path Solution - self._solution = {'trunk_sid': trunk_sid, 'sid': sid, } - self._uri = '/Trunks/{trunk_sid}/OriginationUrls/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OriginationUrlInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OriginationUrlInstance: """ Fetch the OriginationUrlInstance + :returns: The fetched OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OriginationUrlInstance and return response metadata + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OriginationUrlInstance: + """ + Asynchronous coroutine to fetch the OriginationUrlInstance + + + :returns: The fetched OriginationUrlInstance + """ + payload, _, _ = await self._fetch_async() 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): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Deletes the OriginationUrlInstance + Asynchronous coroutine to fetch the OriginationUrlInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._fetch_async() + instance = OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - def update(self, weight=values.unset, priority=values.unset, - enabled=values.unset, friendly_name=values.unset, - sip_url=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: """ 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._update( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + return OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the OriginationUrlInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + instance = OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Accept"] = "application/json" + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> OriginationUrlInstance: + """ + Asynchronous coroutine to update the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: The updated OriginationUrlInstance + """ + payload, _, _ = await self._update_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) 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): + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the OriginationUrlInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + instance = OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ Provide 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'), +class OriginationUrlPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> OriginationUrlInstance: + """ + Build an instance of OriginationUrlInstance + + :param payload: Payload response from the API + """ + + return OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class OriginationUrlList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): + """ + Initialize the OriginationUrlList + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the OriginationUrl. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, } + self._uri = "/Trunks/{trunk_sid}/OriginationUrls".format(**self._solution) + + def _create( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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"}) - # Context - self._context = None - self._solution = {'trunk_sid': trunk_sid, 'sid': sid or self._properties['sid'], } + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def _proxy(self): + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> OriginationUrlInstance: """ - 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 OriginationUrlInstance - :returns: OriginationUrlContext for this OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext + :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 """ - if self._context is None: - self._context = OriginationUrlContext( - self._version, - trunk_sid=self._solution['trunk_sid'], - sid=self._solution['sid'], - ) - return self._context + payload, _, _ = self._create( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + return OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) - @property - def account_sid(self): + def create_with_http_info( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Create the OriginationUrlInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['account_sid'] + payload, status_code, headers = self._create( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + instance = OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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"}) - @property - def sid(self): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> OriginationUrlInstance: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Asynchronously create the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + + :returns: The created OriginationUrlInstance """ - return self._properties['sid'] + payload, _, _ = await self._create_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + return OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) - @property - def trunk_sid(self): + async def create_with_http_info_async( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> ApiResponse: """ - :returns: The SID of the Trunk that owns the Origination URL - :rtype: unicode + Asynchronously create the OriginationUrlInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['trunk_sid'] + payload, status_code, headers = await self._create_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + instance = OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def weight(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OriginationUrlInstance]: """ - :returns: The value that determines the relative load the URI should receive compared to others with the same priority - :rtype: unicode + Streams OriginationUrlInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['weight'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def enabled(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[OriginationUrlInstance]: """ - :returns: Whether the URL is enabled - :rtype: bool + Asynchronously streams OriginationUrlInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['enabled'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def sip_url(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The SIP address you want Twilio to route your Origination calls to - :rtype: unicode + Streams OriginationUrlInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['sip_url'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def friendly_name(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Asynchronously streams OriginationUrlInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def priority(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OriginationUrlInstance]: """ - :returns: The relative importance of the URI - :rtype: unicode + Lists OriginationUrlInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['priority'] - @property - def date_created(self): + return 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]: """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + Asynchronously lists OriginationUrlInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['date_created'] - @property - def date_updated(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + Lists OriginationUrlInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['date_updated'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def url(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The absolute URL of the resource - :rtype: unicode + Asynchronously lists OriginationUrlInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['url'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - 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, + ) -> OriginationUrlPage: """ - Fetch the OriginationUrlInstance + Retrieve a single page of OriginationUrlInstance records from the API. + Request is executed immediately - :returns: The fetched OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance + :param page_token: PageToken provided by the API + :param page_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 """ - return self._proxy.fetch() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - def delete(self): + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OriginationUrlPage(self._version, response, solution=self._solution) + + async def 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: """ - Deletes the OriginationUrlInstance + Asynchronously retrieve a single page of OriginationUrlInstance 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 OriginationUrlInstance """ - 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, weight=values.unset, priority=values.unset, - enabled=values.unset, friendly_name=values.unset, - sip_url=values.unset): + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OriginationUrlPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Update the OriginationUrlInstance + Retrieve a single page with response metadata - :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 updated OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OriginationUrlPage, status code, and headers """ - return self._proxy.update( - weight=weight, - priority=priority, - enabled=enabled, - friendly_name=friendly_name, - sip_url=sip_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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OriginationUrlPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OriginationUrlPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OriginationUrlPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> OriginationUrlPage: + """ + Retrieve a specific page of OriginationUrlInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OriginationUrlInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OriginationUrlPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> OriginationUrlPage: + """ + Asynchronously retrieve a specific page of OriginationUrlInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OriginationUrlInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OriginationUrlPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> OriginationUrlContext: + """ + Constructs a OriginationUrlContext + + :param sid: The unique string that we created to identify the OriginationUrl resource to update. + """ + return OriginationUrlContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __call__(self, sid: str) -> OriginationUrlContext: + """ + Constructs a OriginationUrlContext + + :param sid: The unique string that we created to identify the OriginationUrl resource to update. + """ + return OriginationUrlContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 b7fcc3f958..20abc377fb 100644 --- a/twilio/rest/trunking/v1/trunk/phone_number.py +++ b/twilio/rest/trunking/v1/trunk/phone_number.py @@ -1,559 +1,938 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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: + :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[str] = 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, + } - :returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberList - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberList + self._context: Optional[PhoneNumberContext] = None + + @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) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PhoneNumberInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.delete_with_http_info() - page = self.page(page_size=limits['page_size'], ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists PhoneNumberInstance 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_with_http_info_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) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance - :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 self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "PhoneNumberInstance": """ - Retrieve a single page of PhoneNumberInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch 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 - :returns: Page of PhoneNumberInstance - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberPage + :returns: The fetched PhoneNumberInstance """ - 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info - return PhoneNumberPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of PhoneNumberInstance records from the API. - Request is executed immediately + return self._proxy.fetch_with_http_info() - :param str target_url: API-generated URL for the requested results page + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info - :returns: Page of PhoneNumberInstance - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.fetch_with_http_info_async() - 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.trunking.v1.trunk.phone_number.PhoneNumberContext - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberContext + def __init__(self, version: Version, trunk_sid: str, sid: str): """ - return PhoneNumberContext(self._version, trunk_sid=self._solution['trunk_sid'], sid=sid, ) + Initialize the PhoneNumberContext - def __call__(self, sid): + :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. """ - Constructs a PhoneNumberContext + 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}/PhoneNumbers/{sid}".format(**self._solution) - :returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberContext - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberContext + def _delete(self) -> tuple: """ - return PhoneNumberContext(self._version, trunk_sid=self._solution['trunk_sid'], sid=sid, ) + Internal helper for delete operation - def __repr__(self): + Returns: + tuple: (success_boolean, status_code, headers) """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return '' + Deletes the PhoneNumberInstance -class PhoneNumberPage(Page): - """ """ + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success - def __init__(self, version, response, solution): + def delete_with_http_info(self) -> ApiResponse: """ - Initialize the PhoneNumberPage + Deletes the PhoneNumberInstance and return response metadata - :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 - :returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberPage - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberPage + :returns: ApiResponse with success boolean, status code, and headers """ - super(PhoneNumberPage, self).__init__(version, response) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - # Path Solution - self._solution = solution + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation - def get_instance(self, payload): + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of PhoneNumberInstance - :param dict payload: Payload response from the API + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberInstance - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberInstance + async def delete_async(self) -> bool: """ - return PhoneNumberInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], ) + Asynchronous coroutine that deletes the PhoneNumberInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = await self._delete_async() + return success - :returns: Machine friendly representation - :rtype: str + async def delete_with_http_info_async(self) -> ApiResponse: """ - return '' + Asynchronous coroutine that deletes the PhoneNumberInstance and return response metadata -class PhoneNumberContext(InstanceContext): - """ """ - - def __init__(self, version, trunk_sid, sid): + :returns: ApiResponse with success boolean, status code, and headers """ - Initialize the PhoneNumberContext + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :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 + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberContext - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberContext + Returns: + tuple: (payload, status_code, headers) """ - super(PhoneNumberContext, self).__init__(version) - # Path Solution - self._solution = {'trunk_sid': trunk_sid, 'sid': sid, } - self._uri = '/Trunks/{trunk_sid}/PhoneNumbers/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PhoneNumberInstance: """ Fetch the PhoneNumberInstance + :returns: The fetched PhoneNumberInstance - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - + payload, _, _ = self._fetch() return PhoneNumberInstance( 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 fetch_with_http_info(self) -> ApiResponse: """ - Deletes the PhoneNumberInstance + Fetch the PhoneNumberInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = self._fetch() + instance = PhoneNumberInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) -class PhoneNumberInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - class AddressRequirement(object): - NONE = "none" - ANY = "any" - LOCAL = "local" - FOREIGN = "foreign" + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - 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'), - } + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance - # Context - self._context = None - self._solution = {'trunk_sid': trunk_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): + :returns: The fetched PhoneNumberInstance """ - 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._fetch_async() + return PhoneNumberInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) - :returns: PhoneNumberContext for this PhoneNumberInstance - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberContext + async def fetch_with_http_info_async(self) -> ApiResponse: """ - if self._context is None: - self._context = PhoneNumberContext( - self._version, - trunk_sid=self._solution['trunk_sid'], - sid=self._solution['sid'], - ) - return self._context + Asynchronous coroutine to fetch the PhoneNumberInstance and return response metadata - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def address_requirements(self): + :returns: ApiResponse with instance, status code, and headers """ - :returns: Whether the phone number requires an Address registered with Twilio - :rtype: PhoneNumberInstance.AddressRequirement - """ - return self._properties['address_requirements'] + payload, status_code, headers = await self._fetch_async() + instance = PhoneNumberInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def api_version(self): + def __repr__(self) -> str: """ - :returns: The API version used to start a new TwiML session - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['api_version'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def beta(self): + +class PhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: """ - :returns: Whether the phone number is new to the Twilio platform - :rtype: bool + Build an instance of PhoneNumberInstance + + :param payload: Payload response from the API """ - return self._properties['beta'] - @property - def capabilities(self): + return PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def __repr__(self) -> str: """ - :returns: Indicate if a phone can receive calls or messages - :rtype: dict + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['capabilities'] + return "" - @property - def date_created(self): + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + Initialize the PhoneNumberList + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the PhoneNumber resources. + """ - return self._properties['date_created'] + super().__init__(version) - @property - def date_updated(self): + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + } + self._uri = "/Trunks/{trunk_sid}/PhoneNumbers".format(**self._solution) + + def _create(self, phone_number_sid: str) -> tuple: """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['date_updated'] - @property - def friendly_name(self): + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, phone_number_sid: str) -> PhoneNumberInstance: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Create the PhoneNumberInstance + + :param phone_number_sid: The SID of the [Incoming Phone Number](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) that you want to associate with the trunk. + + :returns: The created PhoneNumberInstance """ - return self._properties['friendly_name'] + payload, _, _ = self._create(phone_number_sid=phone_number_sid) + return PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) - @property - def links(self): + def create_with_http_info(self, phone_number_sid: str) -> ApiResponse: """ - :returns: The URLs of related resources - :rtype: unicode + Create the PhoneNumberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['links'] + payload, status_code, headers = self._create(phone_number_sid=phone_number_sid) + instance = PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def phone_number(self): + async def _create_async(self, phone_number_sid: str) -> tuple: """ - :returns: The phone number in E.164 format - :rtype: unicode + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['phone_number'] - @property - def sid(self): + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Asynchronously create the PhoneNumberInstance + + :param phone_number_sid: The SID of the [Incoming Phone Number](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) that you want to associate with the trunk. + + :returns: The created PhoneNumberInstance """ - return self._properties['sid'] + payload, _, _ = await self._create_async(phone_number_sid=phone_number_sid) + return PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) - @property - def sms_application_sid(self): + async def create_with_http_info_async(self, phone_number_sid: str) -> ApiResponse: """ - :returns: The SID of the application that handles SMS messages sent to the phone number - :rtype: unicode + Asynchronously create the PhoneNumberInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['sms_application_sid'] + payload, status_code, headers = await self._create_async( + phone_number_sid=phone_number_sid + ) + instance = PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def sms_fallback_method(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PhoneNumberInstance]: """ - :returns: The HTTP method used with sms_fallback_url - :rtype: unicode + 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['sms_fallback_method'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def sms_fallback_url(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PhoneNumberInstance]: """ - :returns: The URL that we call when an error occurs while retrieving or executing the TwiML - :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['sms_fallback_url'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def sms_method(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The HTTP method to use with sms_url - :rtype: unicode + Streams PhoneNumberInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['sms_method'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def sms_url(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The URL we call when the phone number receives an incoming SMS message - :rtype: unicode + Asynchronously streams PhoneNumberInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['sms_url'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def status_callback(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: """ - :returns: The URL to send status information to your application - :rtype: unicode + 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['status_callback'] - @property - def status_callback_method(self): + return 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]: """ - :returns: The HTTP method we use to call status_callback - :rtype: unicode + 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['status_callback_method'] - @property - def trunk_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Trunk that handles calls to the phone number - :rtype: unicode + Lists PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['trunk_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def url(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The absolute URL of the resource - :rtype: unicode + Asynchronously lists PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['url'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def voice_application_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, + ) -> PhoneNumberPage: """ - :returns: The SID of the application that handles calls to the phone number - :rtype: unicode + Retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PhoneNumberInstance """ - return self._properties['voice_application_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def voice_caller_id_lookup(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, solution=self._solution) + + async def 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: Whether to lookup the caller's name - :rtype: bool + 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['voice_caller_id_lookup'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def voice_fallback_method(self): + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The HTTP method that we use to call voice_fallback_url - :rtype: unicode + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PhoneNumberPage, status code, and headers """ - return self._properties['voice_fallback_method'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def voice_fallback_url(self): + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The URL we call when an error occurs in TwiML - :rtype: unicode + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PhoneNumberPage, status code, and headers """ - return self._properties['voice_fallback_url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def voice_method(self): + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..5e29ae8205 --- /dev/null +++ b/twilio/rest/trunking/v1/trunk/recording.py @@ -0,0 +1,471 @@ +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.api_response import ApiResponse +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> ApiResponse: + """ + Update the RecordingInstance with HTTP info + + :param mode: + :param trim: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + mode=mode, + trim=trim, + ) + + async def update_with_http_info_async( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RecordingInstance with HTTP info + + :param mode: + :param trim: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + payload, _, _ = self._fetch() + return RecordingInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RecordingInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + payload, _, _ = await self._fetch_async() + return RecordingInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RecordingInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Mode": mode, + "Trim": trim, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(mode=mode, trim=trim) + return RecordingInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def update_with_http_info( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> ApiResponse: + """ + Update the RecordingInstance and return response metadata + + :param mode: + :param trim: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(mode=mode, trim=trim) + instance = RecordingInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Mode": mode, + "Trim": trim, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(mode=mode, trim=trim) + return RecordingInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + async def update_with_http_info_async( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RecordingInstance and return response metadata + + :param mode: + :param trim: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(mode=mode, trim=trim) + instance = RecordingInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..107749eaa4 --- /dev/null +++ b/twilio/rest/trusthub/v1/compliance_inquiries.py @@ -0,0 +1,480 @@ +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.api_response import ApiResponse +from twilio.base.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 update_with_http_info( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the ComplianceInquiriesInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + primary_profile_sid=primary_profile_sid, + theme_set_id=theme_set_id, + ) + + async def update_with_http_info_async( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ComplianceInquiriesInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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 + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + primary_profile_sid=primary_profile_sid, theme_set_id=theme_set_id + ) + return ComplianceInquiriesInstance( + self._version, payload, customer_id=self._solution["customer_id"] + ) + + def update_with_http_info( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the ComplianceInquiriesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + primary_profile_sid=primary_profile_sid, theme_set_id=theme_set_id + ) + instance = ComplianceInquiriesInstance( + self._version, payload, customer_id=self._solution["customer_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + primary_profile_sid=primary_profile_sid, theme_set_id=theme_set_id + ) + return ComplianceInquiriesInstance( + self._version, payload, customer_id=self._solution["customer_id"] + ) + + async def update_with_http_info_async( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ComplianceInquiriesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + primary_profile_sid=primary_profile_sid, theme_set_id=theme_set_id + ) + instance = ComplianceInquiriesInstance( + self._version, payload, customer_id=self._solution["customer_id"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "NotificationEmail": notification_email, + "ThemeSetId": theme_set_id, + "PrimaryProfileSid": primary_profile_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> ComplianceInquiriesInstance: + """ + Create the ComplianceInquiriesInstance + + :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. + :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. + + :returns: The created ComplianceInquiriesInstance + """ + payload, _, _ = self._create( + notification_email=notification_email, + theme_set_id=theme_set_id, + primary_profile_sid=primary_profile_sid, + ) + return ComplianceInquiriesInstance(self._version, payload) + + def create_with_http_info( + self, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ComplianceInquiriesInstance and return response metadata + + :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. + :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. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + notification_email=notification_email, + theme_set_id=theme_set_id, + primary_profile_sid=primary_profile_sid, + ) + instance = ComplianceInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "NotificationEmail": notification_email, + "ThemeSetId": theme_set_id, + "PrimaryProfileSid": primary_profile_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> ComplianceInquiriesInstance: + """ + Asynchronously create the ComplianceInquiriesInstance + + :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. + :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. + + :returns: The created ComplianceInquiriesInstance + """ + payload, _, _ = await self._create_async( + notification_email=notification_email, + theme_set_id=theme_set_id, + primary_profile_sid=primary_profile_sid, + ) + return ComplianceInquiriesInstance(self._version, payload) + + async def create_with_http_info_async( + self, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ComplianceInquiriesInstance and return response metadata + + :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. + :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. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + notification_email=notification_email, + theme_set_id=theme_set_id, + primary_profile_sid=primary_profile_sid, + ) + instance = ComplianceInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..5c5a96de06 --- /dev/null +++ b/twilio/rest/trusthub/v1/compliance_registration_inquiries.py @@ -0,0 +1,1147 @@ +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.api_response import ApiResponse +from twilio.base.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 update_with_http_info( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ComplianceRegistrationInquiriesInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + is_isv_embed=is_isv_embed, + theme_set_id=theme_set_id, + ) + + async def update_with_http_info_async( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ComplianceRegistrationInquiriesInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + is_isv_embed=is_isv_embed, theme_set_id=theme_set_id + ) + return ComplianceRegistrationInquiriesInstance( + self._version, payload, registration_id=self._solution["registration_id"] + ) + + def update_with_http_info( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ComplianceRegistrationInquiriesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + is_isv_embed=is_isv_embed, theme_set_id=theme_set_id + ) + instance = ComplianceRegistrationInquiriesInstance( + self._version, payload, registration_id=self._solution["registration_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + is_isv_embed=is_isv_embed, theme_set_id=theme_set_id + ) + return ComplianceRegistrationInquiriesInstance( + self._version, payload, registration_id=self._solution["registration_id"] + ) + + async def update_with_http_info_async( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ComplianceRegistrationInquiriesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + is_isv_embed=is_isv_embed, theme_set_id=theme_set_id + ) + instance = ComplianceRegistrationInquiriesInstance( + self._version, payload, registration_id=self._solution["registration_id"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + end_user_type=end_user_type, + phone_number_type=phone_number_type, + business_identity_type=business_identity_type, + business_registration_authority=business_registration_authority, + business_legal_name=business_legal_name, + notification_email=notification_email, + accepted_notification_receipt=accepted_notification_receipt, + business_registration_number=business_registration_number, + business_website_url=business_website_url, + friendly_name=friendly_name, + authorized_representative1_first_name=authorized_representative1_first_name, + authorized_representative1_last_name=authorized_representative1_last_name, + authorized_representative1_phone=authorized_representative1_phone, + authorized_representative1_email=authorized_representative1_email, + authorized_representative1_date_of_birth=authorized_representative1_date_of_birth, + address_street=address_street, + address_street_secondary=address_street_secondary, + address_city=address_city, + address_subdivision=address_subdivision, + address_postal_code=address_postal_code, + address_country_code=address_country_code, + emergency_address_street=emergency_address_street, + emergency_address_street_secondary=emergency_address_street_secondary, + emergency_address_city=emergency_address_city, + emergency_address_subdivision=emergency_address_subdivision, + emergency_address_postal_code=emergency_address_postal_code, + emergency_address_country_code=emergency_address_country_code, + use_address_as_emergency_address=use_address_as_emergency_address, + file_name=file_name, + file=file, + first_name=first_name, + last_name=last_name, + date_of_birth=date_of_birth, + individual_email=individual_email, + individual_phone=individual_phone, + is_isv_embed=is_isv_embed, + isv_registering_for_self_or_tenant=isv_registering_for_self_or_tenant, + status_callback_url=status_callback_url, + theme_set_id=theme_set_id, + ) + return ComplianceRegistrationInquiriesInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ComplianceRegistrationInquiriesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + end_user_type=end_user_type, + phone_number_type=phone_number_type, + business_identity_type=business_identity_type, + business_registration_authority=business_registration_authority, + business_legal_name=business_legal_name, + notification_email=notification_email, + accepted_notification_receipt=accepted_notification_receipt, + business_registration_number=business_registration_number, + business_website_url=business_website_url, + friendly_name=friendly_name, + authorized_representative1_first_name=authorized_representative1_first_name, + authorized_representative1_last_name=authorized_representative1_last_name, + authorized_representative1_phone=authorized_representative1_phone, + authorized_representative1_email=authorized_representative1_email, + authorized_representative1_date_of_birth=authorized_representative1_date_of_birth, + address_street=address_street, + address_street_secondary=address_street_secondary, + address_city=address_city, + address_subdivision=address_subdivision, + address_postal_code=address_postal_code, + address_country_code=address_country_code, + emergency_address_street=emergency_address_street, + emergency_address_street_secondary=emergency_address_street_secondary, + emergency_address_city=emergency_address_city, + emergency_address_subdivision=emergency_address_subdivision, + emergency_address_postal_code=emergency_address_postal_code, + emergency_address_country_code=emergency_address_country_code, + use_address_as_emergency_address=use_address_as_emergency_address, + file_name=file_name, + file=file, + first_name=first_name, + last_name=last_name, + date_of_birth=date_of_birth, + individual_email=individual_email, + individual_phone=individual_phone, + is_isv_embed=is_isv_embed, + isv_registering_for_self_or_tenant=isv_registering_for_self_or_tenant, + status_callback_url=status_callback_url, + theme_set_id=theme_set_id, + ) + instance = ComplianceRegistrationInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + end_user_type=end_user_type, + phone_number_type=phone_number_type, + business_identity_type=business_identity_type, + business_registration_authority=business_registration_authority, + business_legal_name=business_legal_name, + notification_email=notification_email, + accepted_notification_receipt=accepted_notification_receipt, + business_registration_number=business_registration_number, + business_website_url=business_website_url, + friendly_name=friendly_name, + authorized_representative1_first_name=authorized_representative1_first_name, + authorized_representative1_last_name=authorized_representative1_last_name, + authorized_representative1_phone=authorized_representative1_phone, + authorized_representative1_email=authorized_representative1_email, + authorized_representative1_date_of_birth=authorized_representative1_date_of_birth, + address_street=address_street, + address_street_secondary=address_street_secondary, + address_city=address_city, + address_subdivision=address_subdivision, + address_postal_code=address_postal_code, + address_country_code=address_country_code, + emergency_address_street=emergency_address_street, + emergency_address_street_secondary=emergency_address_street_secondary, + emergency_address_city=emergency_address_city, + emergency_address_subdivision=emergency_address_subdivision, + emergency_address_postal_code=emergency_address_postal_code, + emergency_address_country_code=emergency_address_country_code, + use_address_as_emergency_address=use_address_as_emergency_address, + file_name=file_name, + file=file, + first_name=first_name, + last_name=last_name, + date_of_birth=date_of_birth, + individual_email=individual_email, + individual_phone=individual_phone, + is_isv_embed=is_isv_embed, + isv_registering_for_self_or_tenant=isv_registering_for_self_or_tenant, + status_callback_url=status_callback_url, + theme_set_id=theme_set_id, + ) + return ComplianceRegistrationInquiriesInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ComplianceRegistrationInquiriesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + end_user_type=end_user_type, + phone_number_type=phone_number_type, + business_identity_type=business_identity_type, + business_registration_authority=business_registration_authority, + business_legal_name=business_legal_name, + notification_email=notification_email, + accepted_notification_receipt=accepted_notification_receipt, + business_registration_number=business_registration_number, + business_website_url=business_website_url, + friendly_name=friendly_name, + authorized_representative1_first_name=authorized_representative1_first_name, + authorized_representative1_last_name=authorized_representative1_last_name, + authorized_representative1_phone=authorized_representative1_phone, + authorized_representative1_email=authorized_representative1_email, + authorized_representative1_date_of_birth=authorized_representative1_date_of_birth, + address_street=address_street, + address_street_secondary=address_street_secondary, + address_city=address_city, + address_subdivision=address_subdivision, + address_postal_code=address_postal_code, + address_country_code=address_country_code, + emergency_address_street=emergency_address_street, + emergency_address_street_secondary=emergency_address_street_secondary, + emergency_address_city=emergency_address_city, + emergency_address_subdivision=emergency_address_subdivision, + emergency_address_postal_code=emergency_address_postal_code, + emergency_address_country_code=emergency_address_country_code, + use_address_as_emergency_address=use_address_as_emergency_address, + file_name=file_name, + file=file, + first_name=first_name, + last_name=last_name, + date_of_birth=date_of_birth, + individual_email=individual_email, + individual_phone=individual_phone, + is_isv_embed=is_isv_embed, + isv_registering_for_self_or_tenant=isv_registering_for_self_or_tenant, + status_callback_url=status_callback_url, + theme_set_id=theme_set_id, + ) + instance = ComplianceRegistrationInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..691594bd4f --- /dev/null +++ b/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py @@ -0,0 +1,822 @@ +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.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ComplianceTollfreeInquiriesInstance(InstanceResource): + + class BusinessType(object): + PRIVATE_PROFIT = "PRIVATE_PROFIT" + PUBLIC_PROFIT = "PUBLIC_PROFIT" + NON_PROFIT = "NON_PROFIT" + SOLE_PROPRIETOR = "SOLE_PROPRIETOR" + GOVERNMENT = "GOVERNMENT" + + 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, + customer_profile_sid: Union[str, object] = values.unset, + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "TollfreePhoneNumber": tollfree_phone_number, + "NotificationEmail": notification_email, + "CustomerProfileSid": customer_profile_sid, + "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 + ), + "BusinessRegistrationNumber": business_registration_number, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessRegistrationCountry": business_registration_country, + "BusinessType": business_type, + "DoingBusinessAs": doing_business_as, + "OptInConfirmationMessage": opt_in_confirmation_message, + "HelpMessageSample": help_message_sample, + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + "AgeGatedContent": serialize.boolean_to_string(age_gated_content), + "ExternalReferenceId": external_reference_id, + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "VettingId": vetting_id, + "VettingProvider": vetting_provider, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + tollfree_phone_number: str, + notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, 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 customer_profile_sid: The Customer Profile Sid associated with the Account. + :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. + :param business_registration_number: The Business Registration Number of the business or organization. + :param business_registration_authority: The Business Registration Authority of the business or organization. + :param business_registration_country: The Business Registration Country of the business or organization. + :param business_type: + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification. + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param external_reference_id: A legally recognized business registration number. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_id: Unique identifier for the created Vetting . + :param vetting_provider: Name of the vetting provider. + + :returns: The created ComplianceTollfreeInquiriesInstance + """ + payload, _, _ = self._create( + tollfree_phone_number=tollfree_phone_number, + notification_email=notification_email, + customer_profile_sid=customer_profile_sid, + business_name=business_name, + business_website=business_website, + 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, + theme_set_id=theme_set_id, + skip_messaging_use_case=skip_messaging_use_case, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + external_reference_id=external_reference_id, + opt_in_keywords=opt_in_keywords, + vetting_id=vetting_id, + vetting_provider=vetting_provider, + ) + return ComplianceTollfreeInquiriesInstance(self._version, payload) + + def create_with_http_info( + self, + tollfree_phone_number: str, + notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ComplianceTollfreeInquiriesInstance and return response metadata + + :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 customer_profile_sid: The Customer Profile Sid associated with the Account. + :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. + :param business_registration_number: The Business Registration Number of the business or organization. + :param business_registration_authority: The Business Registration Authority of the business or organization. + :param business_registration_country: The Business Registration Country of the business or organization. + :param business_type: + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification. + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param external_reference_id: A legally recognized business registration number. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_id: Unique identifier for the created Vetting . + :param vetting_provider: Name of the vetting provider. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + tollfree_phone_number=tollfree_phone_number, + notification_email=notification_email, + customer_profile_sid=customer_profile_sid, + business_name=business_name, + business_website=business_website, + 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, + theme_set_id=theme_set_id, + skip_messaging_use_case=skip_messaging_use_case, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + external_reference_id=external_reference_id, + opt_in_keywords=opt_in_keywords, + vetting_id=vetting_id, + vetting_provider=vetting_provider, + ) + instance = ComplianceTollfreeInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + tollfree_phone_number: str, + notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "TollfreePhoneNumber": tollfree_phone_number, + "NotificationEmail": notification_email, + "CustomerProfileSid": customer_profile_sid, + "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 + ), + "BusinessRegistrationNumber": business_registration_number, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessRegistrationCountry": business_registration_country, + "BusinessType": business_type, + "DoingBusinessAs": doing_business_as, + "OptInConfirmationMessage": opt_in_confirmation_message, + "HelpMessageSample": help_message_sample, + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + "AgeGatedContent": serialize.boolean_to_string(age_gated_content), + "ExternalReferenceId": external_reference_id, + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "VettingId": vetting_id, + "VettingProvider": vetting_provider, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + tollfree_phone_number: str, + notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, 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 customer_profile_sid: The Customer Profile Sid associated with the Account. + :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. + :param business_registration_number: The Business Registration Number of the business or organization. + :param business_registration_authority: The Business Registration Authority of the business or organization. + :param business_registration_country: The Business Registration Country of the business or organization. + :param business_type: + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification. + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param external_reference_id: A legally recognized business registration number. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_id: Unique identifier for the created Vetting . + :param vetting_provider: Name of the vetting provider. + + :returns: The created ComplianceTollfreeInquiriesInstance + """ + payload, _, _ = await self._create_async( + tollfree_phone_number=tollfree_phone_number, + notification_email=notification_email, + customer_profile_sid=customer_profile_sid, + business_name=business_name, + business_website=business_website, + 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, + theme_set_id=theme_set_id, + skip_messaging_use_case=skip_messaging_use_case, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + external_reference_id=external_reference_id, + opt_in_keywords=opt_in_keywords, + vetting_id=vetting_id, + vetting_provider=vetting_provider, + ) + return ComplianceTollfreeInquiriesInstance(self._version, payload) + + async def create_with_http_info_async( + self, + tollfree_phone_number: str, + notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, + 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, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ComplianceTollfreeInquiriesInstance and return response metadata + + :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 customer_profile_sid: The Customer Profile Sid associated with the Account. + :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. + :param business_registration_number: The Business Registration Number of the business or organization. + :param business_registration_authority: The Business Registration Authority of the business or organization. + :param business_registration_country: The Business Registration Country of the business or organization. + :param business_type: + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification. + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param external_reference_id: A legally recognized business registration number. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_id: Unique identifier for the created Vetting . + :param vetting_provider: Name of the vetting provider. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + tollfree_phone_number=tollfree_phone_number, + notification_email=notification_email, + customer_profile_sid=customer_profile_sid, + business_name=business_name, + business_website=business_website, + 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, + theme_set_id=theme_set_id, + skip_messaging_use_case=skip_messaging_use_case, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + external_reference_id=external_reference_id, + opt_in_keywords=opt_in_keywords, + vetting_id=vetting_id, + vetting_provider=vetting_provider, + ) + instance = ComplianceTollfreeInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..5ba9df5ecb --- /dev/null +++ b/twilio/rest/trusthub/v1/customer_profiles/__init__.py @@ -0,0 +1,1422 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomerProfilesInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CustomerProfilesInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CustomerProfilesInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the CustomerProfilesInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomerProfilesInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomerProfilesInstance: + """ + Fetch the CustomerProfilesInstance + + + :returns: The fetched CustomerProfilesInstance + """ + payload, _, _ = self._fetch() + return CustomerProfilesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CustomerProfilesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CustomerProfilesInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesInstance + + + :returns: The fetched CustomerProfilesInstance + """ + payload, _, _ = await self._fetch_async() + return CustomerProfilesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CustomerProfilesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + return CustomerProfilesInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CustomerProfilesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + instance = CustomerProfilesInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + return CustomerProfilesInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CustomerProfilesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + instance = CustomerProfilesInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + return CustomerProfilesInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CustomerProfilesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + instance = CustomerProfilesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + return CustomerProfilesInstance(self._version, payload) + + async def create_with_http_info_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CustomerProfilesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + instance = CustomerProfilesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams CustomerProfilesInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams CustomerProfilesInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists CustomerProfilesInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists CustomerProfilesInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with CustomerProfilesPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CustomerProfilesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with CustomerProfilesPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CustomerProfilesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..f0b451d0fa --- /dev/null +++ b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_channel_endpoint_assignment.py @@ -0,0 +1,1029 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomerProfilesChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomerProfilesChannelEndpointAssignmentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesChannelEndpointAssignmentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Fetch the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance + """ + payload, _, _ = self._fetch() + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesChannelEndpointAssignmentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance + """ + payload, _, _ = await self._fetch_async() + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesChannelEndpointAssignmentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def create_with_http_info( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> ApiResponse: + """ + Create the CustomerProfilesChannelEndpointAssignmentInstance and return response metadata + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) + instance = CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + async def create_with_http_info_async( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> ApiResponse: + """ + Asynchronously create the CustomerProfilesChannelEndpointAssignmentInstance and return response metadata + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) + instance = CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams CustomerProfilesChannelEndpointAssignmentInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams CustomerProfilesChannelEndpointAssignmentInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists CustomerProfilesChannelEndpointAssignmentInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists CustomerProfilesChannelEndpointAssignmentInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution + ) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with CustomerProfilesChannelEndpointAssignmentPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CustomerProfilesChannelEndpointAssignmentPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with CustomerProfilesChannelEndpointAssignmentPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CustomerProfilesChannelEndpointAssignmentPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..992ac98822 --- /dev/null +++ b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_entity_assignments.py @@ -0,0 +1,963 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomerProfilesEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the CustomerProfilesEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomerProfilesEntityAssignmentsInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesEntityAssignmentsInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomerProfilesEntityAssignmentsInstance: + """ + Fetch the CustomerProfilesEntityAssignmentsInstance + + + :returns: The fetched CustomerProfilesEntityAssignmentsInstance + """ + payload, _, _ = self._fetch() + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesEntityAssignmentsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CustomerProfilesEntityAssignmentsInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesEntityAssignmentsInstance + + + :returns: The fetched CustomerProfilesEntityAssignmentsInstance + """ + payload, _, _ = await self._fetch_async() + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesEntityAssignmentsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(object_sid=object_sid) + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def create_with_http_info(self, object_sid: str) -> ApiResponse: + """ + Create the CustomerProfilesEntityAssignmentsInstance and return response metadata + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(object_sid=object_sid) + instance = CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, object_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(object_sid=object_sid) + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + async def create_with_http_info_async(self, object_sid: str) -> ApiResponse: + """ + Asynchronously create the CustomerProfilesEntityAssignmentsInstance and return response metadata + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(object_sid=object_sid) + instance = CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CustomerProfilesEntityAssignmentsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + object_type=object_type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CustomerProfilesEntityAssignmentsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + object_type=object_type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CustomerProfilesEntityAssignmentsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CustomerProfilesEntityAssignmentsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution + ) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with CustomerProfilesEntityAssignmentsPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CustomerProfilesEntityAssignmentsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with CustomerProfilesEntityAssignmentsPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CustomerProfilesEntityAssignmentsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..7094e1c0f9 --- /dev/null +++ b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py @@ -0,0 +1,826 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesEvaluationsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesEvaluationsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomerProfilesEvaluationsInstance: + """ + Fetch the CustomerProfilesEvaluationsInstance + + + :returns: The fetched CustomerProfilesEvaluationsInstance + """ + payload, _, _ = self._fetch() + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesEvaluationsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CustomerProfilesEvaluationsInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesEvaluationsInstance + + + :returns: The fetched CustomerProfilesEvaluationsInstance + """ + payload, _, _ = await self._fetch_async() + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesEvaluationsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(policy_sid=policy_sid) + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def create_with_http_info(self, policy_sid: str) -> ApiResponse: + """ + Create the CustomerProfilesEvaluationsInstance and return response metadata + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(policy_sid=policy_sid) + instance = CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, policy_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(policy_sid=policy_sid) + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + async def create_with_http_info_async(self, policy_sid: str) -> ApiResponse: + """ + Asynchronously create the CustomerProfilesEvaluationsInstance and return response metadata + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(policy_sid=policy_sid) + instance = CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CustomerProfilesEvaluationsInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CustomerProfilesEvaluationsInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CustomerProfilesEvaluationsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CustomerProfilesEvaluationsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution + ) + + async def 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, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CustomerProfilesEvaluationsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CustomerProfilesEvaluationsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CustomerProfilesEvaluationsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CustomerProfilesEvaluationsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..bb7c7740b8 --- /dev/null +++ b/twilio/rest/trusthub/v1/end_user.py @@ -0,0 +1,1106 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EndUserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EndUserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the EndUserInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the EndUserInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EndUserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EndUserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EndUserInstance: + """ + Fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + payload, _, _ = self._fetch() + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> EndUserInstance: + """ + Asynchronous coroutine to fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + payload, _, _ = await self._fetch_async() + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(friendly_name=friendly_name, attributes=attributes) + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the EndUserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, attributes=attributes + ) + instance = EndUserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the EndUserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) + instance = EndUserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return EndUserInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Create the EndUserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = EndUserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return EndUserInstance(self._version, payload) + + async def create_with_http_info_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the EndUserInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = EndUserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EndUserInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EndUserInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EndUserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EndUserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EndUserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EndUserPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EndUserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EndUserPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..8f2da577fb --- /dev/null +++ b/twilio/rest/trusthub/v1/end_user_type.py @@ -0,0 +1,649 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EndUserTypeInstance: + """ + Fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + payload, _, _ = self._fetch() + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserTypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> EndUserTypeInstance: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + payload, _, _ = await self._fetch_async() + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EndUserTypeInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EndUserTypeInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EndUserTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EndUserTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EndUserTypePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EndUserTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EndUserTypePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EndUserTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..ed7035da27 --- /dev/null +++ b/twilio/rest/trusthub/v1/policies.py @@ -0,0 +1,647 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PoliciesInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PoliciesInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PoliciesInstance: + """ + Fetch the PoliciesInstance + + + :returns: The fetched PoliciesInstance + """ + payload, _, _ = self._fetch() + return PoliciesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PoliciesInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PoliciesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> PoliciesInstance: + """ + Asynchronous coroutine to fetch the PoliciesInstance + + + :returns: The fetched PoliciesInstance + """ + payload, _, _ = await self._fetch_async() + return PoliciesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PoliciesInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PoliciesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PoliciesInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PoliciesInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PoliciesInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PoliciesInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PoliciesPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PoliciesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PoliciesPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PoliciesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..8020232292 --- /dev/null +++ b/twilio/rest/trusthub/v1/supporting_document.py @@ -0,0 +1,1129 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the SupportingDocumentInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SupportingDocumentInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SupportingDocumentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SupportingDocumentInstance: + """ + Fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + payload, _, _ = self._fetch() + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SupportingDocumentInstance: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + payload, _, _ = await self._fetch_async() + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(friendly_name=friendly_name, attributes=attributes) + return SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the SupportingDocumentInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, attributes=attributes + ) + instance = SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) + return SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SupportingDocumentInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) + instance = SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return SupportingDocumentInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Create the SupportingDocumentInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = SupportingDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return SupportingDocumentInstance(self._version, payload) + + async def create_with_http_info_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SupportingDocumentInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = SupportingDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SupportingDocumentInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SupportingDocumentInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SupportingDocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SupportingDocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SupportingDocumentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SupportingDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SupportingDocumentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SupportingDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..2ae6cb345e --- /dev/null +++ b/twilio/rest/trusthub/v1/supporting_document_type.py @@ -0,0 +1,649 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SupportingDocumentTypeInstance: + """ + Fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + payload, _, _ = self._fetch() + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentTypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SupportingDocumentTypeInstance: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + payload, _, _ = await self._fetch_async() + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SupportingDocumentTypeInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SupportingDocumentTypeInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SupportingDocumentTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SupportingDocumentTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SupportingDocumentTypePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SupportingDocumentTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SupportingDocumentTypePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SupportingDocumentTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..3c2553dbbe --- /dev/null +++ b/twilio/rest/trusthub/v1/trust_products/__init__.py @@ -0,0 +1,1412 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrustProductsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the TrustProductsInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TrustProductsInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the TrustProductsInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrustProductsInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrustProductsInstance: + """ + Fetch the TrustProductsInstance + + + :returns: The fetched TrustProductsInstance + """ + payload, _, _ = self._fetch() + return TrustProductsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TrustProductsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TrustProductsInstance: + """ + Asynchronous coroutine to fetch the TrustProductsInstance + + + :returns: The fetched TrustProductsInstance + """ + payload, _, _ = await self._fetch_async() + return TrustProductsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TrustProductsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + return TrustProductsInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the TrustProductsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + instance = TrustProductsInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + return TrustProductsInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TrustProductsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + instance = TrustProductsInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + return TrustProductsInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the TrustProductsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + instance = TrustProductsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + return TrustProductsInstance(self._version, payload) + + async def create_with_http_info_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TrustProductsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + instance = TrustProductsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams TrustProductsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams TrustProductsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists TrustProductsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists TrustProductsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with TrustProductsPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TrustProductsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with TrustProductsPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TrustProductsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..0f16a1a57c --- /dev/null +++ b/twilio/rest/trusthub/v1/trust_products/trust_products_channel_endpoint_assignment.py @@ -0,0 +1,1029 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrustProductsChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the TrustProductsChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrustProductsChannelEndpointAssignmentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsChannelEndpointAssignmentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Fetch the TrustProductsChannelEndpointAssignmentInstance + + + :returns: The fetched TrustProductsChannelEndpointAssignmentInstance + """ + payload, _, _ = self._fetch() + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsChannelEndpointAssignmentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Asynchronous coroutine to fetch the TrustProductsChannelEndpointAssignmentInstance + + + :returns: The fetched TrustProductsChannelEndpointAssignmentInstance + """ + payload, _, _ = await self._fetch_async() + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsChannelEndpointAssignmentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def create_with_http_info( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> ApiResponse: + """ + Create the TrustProductsChannelEndpointAssignmentInstance and return response metadata + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) + instance = TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + async def create_with_http_info_async( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> ApiResponse: + """ + Asynchronously create the TrustProductsChannelEndpointAssignmentInstance and return response metadata + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) + instance = TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams TrustProductsChannelEndpointAssignmentInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams TrustProductsChannelEndpointAssignmentInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists TrustProductsChannelEndpointAssignmentInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists TrustProductsChannelEndpointAssignmentInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution + ) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with TrustProductsChannelEndpointAssignmentPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TrustProductsChannelEndpointAssignmentPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with TrustProductsChannelEndpointAssignmentPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TrustProductsChannelEndpointAssignmentPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..f4525abc80 --- /dev/null +++ b/twilio/rest/trusthub/v1/trust_products/trust_products_entity_assignments.py @@ -0,0 +1,957 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrustProductsEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the TrustProductsEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrustProductsEntityAssignmentsInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsEntityAssignmentsInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrustProductsEntityAssignmentsInstance: + """ + Fetch the TrustProductsEntityAssignmentsInstance + + + :returns: The fetched TrustProductsEntityAssignmentsInstance + """ + payload, _, _ = self._fetch() + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsEntityAssignmentsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TrustProductsEntityAssignmentsInstance: + """ + Asynchronous coroutine to fetch the TrustProductsEntityAssignmentsInstance + + + :returns: The fetched TrustProductsEntityAssignmentsInstance + """ + payload, _, _ = await self._fetch_async() + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsEntityAssignmentsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(object_sid=object_sid) + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def create_with_http_info(self, object_sid: str) -> ApiResponse: + """ + Create the TrustProductsEntityAssignmentsInstance and return response metadata + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(object_sid=object_sid) + instance = TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, object_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(object_sid=object_sid) + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + async def create_with_http_info_async(self, object_sid: str) -> ApiResponse: + """ + Asynchronously create the TrustProductsEntityAssignmentsInstance and return response metadata + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(object_sid=object_sid) + instance = TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TrustProductsEntityAssignmentsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + object_type=object_type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TrustProductsEntityAssignmentsInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + object_type=object_type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TrustProductsEntityAssignmentsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TrustProductsEntityAssignmentsInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution + ) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with TrustProductsEntityAssignmentsPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TrustProductsEntityAssignmentsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with TrustProductsEntityAssignmentsPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TrustProductsEntityAssignmentsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..f27af2615f --- /dev/null +++ b/twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py @@ -0,0 +1,820 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsEvaluationsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsEvaluationsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrustProductsEvaluationsInstance: + """ + Fetch the TrustProductsEvaluationsInstance + + + :returns: The fetched TrustProductsEvaluationsInstance + """ + payload, _, _ = self._fetch() + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsEvaluationsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TrustProductsEvaluationsInstance: + """ + Asynchronous coroutine to fetch the TrustProductsEvaluationsInstance + + + :returns: The fetched TrustProductsEvaluationsInstance + """ + payload, _, _ = await self._fetch_async() + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsEvaluationsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(policy_sid=policy_sid) + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def create_with_http_info(self, policy_sid: str) -> ApiResponse: + """ + Create the TrustProductsEvaluationsInstance and return response metadata + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(policy_sid=policy_sid) + instance = TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, policy_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(policy_sid=policy_sid) + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + async def create_with_http_info_async(self, policy_sid: str) -> ApiResponse: + """ + Asynchronously create the TrustProductsEvaluationsInstance and return response metadata + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(policy_sid=policy_sid) + instance = TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TrustProductsEvaluationsInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TrustProductsEvaluationsInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TrustProductsEvaluationsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TrustProductsEvaluationsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution + ) + + async def 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, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TrustProductsEvaluationsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TrustProductsEvaluationsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TrustProductsEvaluationsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TrustProductsEvaluationsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 7caef9a66a..a66b3333b0 100644 --- a/twilio/rest/verify/__init__.py +++ b/twilio/rest/verify/__init__.py @@ -1,53 +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 forms(self) -> FormList: + warn( + "forms is deprecated. Use v2.forms instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.forms @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 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 + + @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 - :returns: Machine friendly representation - :rtype: str - """ - return '' + @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 15490ff475..01bee13b0d 100644 --- a/twilio/rest/verify/v2/__init__.py +++ b/twilio/rest/verify/v2/__init__.py @@ -1,42 +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._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 services(self): - """ - :rtype: twilio.rest.verify.v2.service.ServiceList - """ + def forms(self) -> FormList: + if self._forms is None: + self._forms = FormList(self) + return self._forms + + @property + def safelist(self) -> SafelistList: + if self._safelist is None: + self._safelist = SafelistList(self) + return self._safelist + + @property + def services(self) -> ServiceList: if self._services is None: self._services = ServiceList(self) return self._services - 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 new file mode 100644 index 0000000000..223f6b6d15 --- /dev/null +++ b/twilio/rest/verify/v2/form.py @@ -0,0 +1,266 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class FormInstance(InstanceResource): + + class FormTypes(object): + FORM_PUSH = "form-push" + + """ + :ivar form_type: + :ivar forms: Object that contains the available forms for this type. This available forms are given in the standard [JSON Schema](https://json-schema.org/) format + :ivar form_meta: Additional information for the available forms for this type. E.g. The separator string used for `binding` in a Factor push. + :ivar url: The URL to access the forms for this type. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + form_type: Optional[FormTypes] = None, + ): + super().__init__(version) + + self.form_type: Optional["FormInstance.FormTypes"] = payload.get("form_type") + self.forms: Optional[Dict[str, object]] = payload.get("forms") + self.form_meta: Optional[Dict[str, object]] = payload.get("form_meta") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "form_type": form_type or self.form_type, + } + + self._context: Optional[FormContext] = None + + @property + def _proxy(self) -> "FormContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FormContext for this FormInstance + """ + if self._context is None: + self._context = FormContext( + self._version, + form_type=self._solution["form_type"], + ) + return self._context + + def fetch(self) -> "FormInstance": + """ + Fetch the FormInstance + + + :returns: The fetched FormInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FormInstance": + """ + Asynchronous coroutine to fetch the FormInstance + + + :returns: The fetched FormInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FormInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FormInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FormContext(InstanceContext): + + def __init__(self, version: Version, form_type: "FormInstance.FormTypes"): + """ + Initialize the FormContext + + :param version: Version that contains the resource + :param form_type: The Type of this Form. Currently only `form-push` is supported. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "form_type": form_type, + } + self._uri = "/Forms/{form_type}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> FormInstance: + """ + Fetch the FormInstance + + + :returns: The fetched FormInstance + """ + payload, _, _ = self._fetch() + return FormInstance( + self._version, + payload, + form_type=self._solution["form_type"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FormInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FormInstance( + self._version, + payload, + form_type=self._solution["form_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> FormInstance: + """ + Asynchronous coroutine to fetch the FormInstance + + + :returns: The fetched FormInstance + """ + payload, _, _ = await self._fetch_async() + return FormInstance( + self._version, + payload, + form_type=self._solution["form_type"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FormInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FormInstance( + self._version, + payload, + form_type=self._solution["form_type"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 FormList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FormList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, form_type: "FormInstance.FormTypes") -> FormContext: + """ + Constructs a FormContext + + :param form_type: The Type of this Form. Currently only `form-push` is supported. + """ + return FormContext(self._version, form_type=form_type) + + def __call__(self, form_type: "FormInstance.FormTypes") -> FormContext: + """ + Constructs a FormContext + + :param form_type: The Type of this Form. Currently only `form-push` is supported. + """ + return FormContext(self._version, form_type=form_type) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/verify/v2/safelist.py b/twilio/rest/verify/v2/safelist.py new file mode 100644 index 0000000000..9ea8069e48 --- /dev/null +++ b/twilio/rest/verify/v2/safelist.py @@ -0,0 +1,460 @@ +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.api_response import ApiResponse +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SafelistInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SafelistInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SafelistInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SafelistInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the SafelistInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SafelistInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SafelistInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SafelistInstance: + """ + Fetch the SafelistInstance + + + :returns: The fetched SafelistInstance + """ + payload, _, _ = self._fetch() + return SafelistInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SafelistInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SafelistInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SafelistInstance: + """ + Asynchronous coroutine to fetch the SafelistInstance + + + :returns: The fetched SafelistInstance + """ + payload, _, _ = await self._fetch_async() + return SafelistInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SafelistInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SafelistInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(phone_number=phone_number) + return SafelistInstance(self._version, payload) + + def create_with_http_info(self, phone_number: str) -> ApiResponse: + """ + Create the SafelistInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(phone_number=phone_number) + instance = SafelistInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, phone_number: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(phone_number=phone_number) + return SafelistInstance(self._version, payload) + + async def create_with_http_info_async(self, phone_number: str) -> ApiResponse: + """ + Asynchronously create the SafelistInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number + ) + instance = SafelistInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 e845c890ed..ed9b7747be 100644 --- a/twilio/rest/verify/v2/service/__init__.py +++ b/twilio/rest/verify/v2/service/__init__.py @@ -1,564 +1,1067 @@ -# 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, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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.messaging_configuration import MessagingConfigurationList +from twilio.rest.verify.v2.service.access_token import AccessTokenList +from twilio.rest.verify.v2.service.approve_challenge import ApproveChallengeList +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.new_challenge import NewChallengeList +from twilio.rest.verify.v2.service.new_factor import NewFactorList +from twilio.rest.verify.v2.service.new_verify_factor import NewVerifyFactorList 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): - """ """ +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 passkeys: + :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.passkeys: Optional[Dict[str, object]] = payload.get("passkeys") + 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") - def __init__(self, version): - """ - Initialize the ServiceList + self._solution = { + "sid": sid or self.sid, + } - :param Version version: Version that contains the resource + 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) + 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, 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): + def delete(self) -> bool: """ - Create the ServiceInstance + Deletes 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. - :returns: The created ServiceInstance - :rtype: twilio.rest.verify.v2.service.ServiceInstance + :returns: True if delete succeeds, False otherwise """ - 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, - }) + 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 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 await self._proxy.delete_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.verify.v2.service.ServiceInstance] + def delete_with_http_info(self) -> ApiResponse: """ - limits = self._version.read_limits(limit, page_size) + Deletes the ServiceInstance with HTTP info - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() - def list(self, limit=None, page_size=None): + async def delete_with_http_info_async(self) -> ApiResponse: """ - 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 with HTTP info - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_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.verify.v2.service.ServicePage + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Asynchronous coroutine to fetch the ServiceInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return ServicePage(self._version, response, self._solution) + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() - def get_page(self, target_url): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately + Fetch the ServiceInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of ServiceInstance - :rtype: twilio.rest.verify.v2.service.ServicePage + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ServicePage(self._version, response, self._solution) + return self._proxy.fetch_with_http_info() - def get(self, sid): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Constructs a ServiceContext + Asynchronous coroutine to fetch the ServiceInstance with HTTP info - :param sid: The unique string that identifies the resource - :returns: twilio.rest.verify.v2.service.ServiceContext - :rtype: twilio.rest.verify.v2.service.ServiceContext + :returns: ApiResponse with instance, status code, and headers """ - return ServiceContext(self._version, sid=sid, ) + return await self._proxy.fetch_with_http_info_async() - def __call__(self, 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, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": """ - Constructs a ServiceContext + Update the ServiceInstance - :param sid: The unique string that identifies the resource + :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 passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured - :returns: twilio.rest.verify.v2.service.ServiceContext - :rtype: twilio.rest.verify.v2.service.ServiceContext + :returns: The updated ServiceInstance """ - return ServiceContext(self._version, sid=sid, ) + 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, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) - def __repr__(self): + 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, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: 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 passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The updated ServiceInstance """ - Provide a friendly representation + 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, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) - :returns: Machine friendly representation - :rtype: str + def update_with_http_info( + 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, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :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 passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + 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, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + + async def update_with_http_info_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, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :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 passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + + @property + def access_tokens(self) -> AccessTokenList: """ - return '' + Access the access_tokens + """ + return self._proxy.access_tokens + @property + def approve_challenge(self) -> ApproveChallengeList: + """ + Access the approve_challenge + """ + return self._proxy.approve_challenge -class ServicePage(Page): - """ """ + @property + def entities(self) -> EntityList: + """ + Access the entities + """ + return self._proxy.entities - def __init__(self, version, response, solution): + @property + def messaging_configurations(self) -> MessagingConfigurationList: + """ + Access the messaging_configurations """ - Initialize the ServicePage + return self._proxy.messaging_configurations - :param Version version: Version that contains the resource - :param Response response: Response from the API + @property + def new_challenge(self) -> NewChallengeList: + """ + Access the new_challenge + """ + return self._proxy.new_challenge - :returns: twilio.rest.verify.v2.service.ServicePage - :rtype: twilio.rest.verify.v2.service.ServicePage + @property + def new_factors(self) -> NewFactorList: """ - super(ServicePage, self).__init__(version, response) + Access the new_factors + """ + return self._proxy.new_factors - # Path Solution - self._solution = solution + @property + def new_verify_factors(self) -> NewVerifyFactorList: + """ + Access the new_verify_factors + """ + return self._proxy.new_verify_factors - def get_instance(self, payload): + @property + def rate_limits(self) -> RateLimitList: """ - Build an instance of ServiceInstance + Access the rate_limits + """ + return self._proxy.rate_limits + + @property + def verifications(self) -> VerificationList: + """ + Access the verifications + """ + return self._proxy.verifications - :param dict payload: Payload response from the API + @property + def verification_checks(self) -> VerificationCheckList: + """ + Access the verification_checks + """ + return self._proxy.verification_checks - :returns: twilio.rest.verify.v2.service.ServiceInstance - :rtype: twilio.rest.verify.v2.service.ServiceInstance + @property + def webhooks(self) -> WebhookList: """ - return ServiceInstance(self._version, payload, ) + Access the webhooks + """ + return self._proxy.webhooks - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class ServiceContext(InstanceContext): - """ """ - def __init__(self, version, sid): + def __init__(self, version: Version, sid: str): """ Initialize the ServiceContext - :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 + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - super(ServiceContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) - # Dependents - self._verifications = None - self._verification_checks = None - self._rate_limits = None - self._messaging_configurations = None + self._access_tokens: Optional[AccessTokenList] = None + self._approve_challenge: Optional[ApproveChallengeList] = None + self._entities: Optional[EntityList] = None + self._messaging_configurations: Optional[MessagingConfigurationList] = None + self._new_challenge: Optional[NewChallengeList] = None + self._new_factors: Optional[NewFactorList] = None + self._new_verify_factors: Optional[NewVerifyFactorList] = None + self._rate_limits: Optional[RateLimitList] = None + self._verifications: Optional[VerificationList] = None + self._verification_checks: Optional[VerificationCheckList] = None + self._webhooks: Optional[WebhookList] = None - def fetch(self): + def _delete(self) -> tuple: """ - Fetch the ServiceInstance + Internal helper for delete operation - :returns: The fetched ServiceInstance - :rtype: twilio.rest.verify.v2.service.ServiceInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - def delete(self): + def delete(self) -> bool: """ Deletes the ServiceInstance + :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + success, _, _ = self._delete() + return success - 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): + def delete_with_http_info(self) -> ApiResponse: """ - Update the ServiceInstance + Deletes the ServiceInstance and return response metadata - :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. - :returns: The updated ServiceInstance - :rtype: twilio.rest.verify.v2.service.ServiceInstance + :returns: ApiResponse with success boolean, status code, and headers """ - 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, - }) + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - - @property - def verifications(self): + async def _delete_async(self) -> tuple: """ - Access the verifications + Internal async helper for delete operation - :returns: twilio.rest.verify.v2.service.verification.VerificationList - :rtype: twilio.rest.verify.v2.service.verification.VerificationList + Returns: + tuple: (success_boolean, status_code, headers) """ - if self._verifications is None: - self._verifications = VerificationList(self._version, service_sid=self._solution['sid'], ) - return self._verifications - @property - def verification_checks(self): - """ - Access the verification_checks + headers = values.of({}) - :returns: twilio.rest.verify.v2.service.verification_check.VerificationCheckList - :rtype: twilio.rest.verify.v2.service.verification_check.VerificationCheckList - """ - if self._verification_checks is None: - self._verification_checks = VerificationCheckList(self._version, service_sid=self._solution['sid'], ) - return self._verification_checks + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - @property - def rate_limits(self): + async def delete_async(self) -> bool: """ - Access the rate_limits + Asynchronous coroutine that deletes the ServiceInstance + - :returns: twilio.rest.verify.v2.service.rate_limit.RateLimitList - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitList + :returns: True if delete succeeds, False otherwise """ - if self._rate_limits is None: - self._rate_limits = RateLimitList(self._version, service_sid=self._solution['sid'], ) - return self._rate_limits + success, _, _ = await self._delete_async() + return success - @property - def messaging_configurations(self): + async def delete_with_http_info_async(self) -> ApiResponse: """ - Access the messaging_configurations + Asynchronous coroutine that deletes the ServiceInstance and return response metadata + - :returns: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationList - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationList + :returns: ApiResponse with success boolean, status code, and headers """ - if self._messaging_configurations is None: - self._messaging_configurations = MessagingConfigurationList( - self._version, - service_sid=self._solution['sid'], - ) - return self._messaging_configurations + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __repr__(self): + def _fetch(self) -> tuple: """ - Provide a friendly representation + Internal helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) -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'), - '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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - @property - def _proxy(self): + def fetch(self) -> ServiceInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Fetch the ServiceInstance - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.verify.v2.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 unique string that identifies the resource - :rtype: unicode + :returns: The fetched ServiceInstance """ - return self._properties['sid'] + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - @property - def account_sid(self): + def fetch_with_http_info(self) -> ApiResponse: """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + Fetch the ServiceInstance and return response metadata - @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 + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['code_length'] + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def lookup_enabled(self): + async def _fetch_async(self) -> tuple: """ - :returns: Whether to perform a lookup with each verification - :rtype: bool - """ - return self._properties['lookup_enabled'] + Internal async helper for fetch operation - @property - def psd2_enabled(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: Whether to pass PSD2 transaction parameters when starting a verification - :rtype: bool - """ - return self._properties['psd2_enabled'] - @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'] + headers = values.of({}) - @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 - """ - return self._properties['dtmf_input_required'] + headers["Accept"] = "application/json" - @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'] + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - @property - def do_not_share_warning_enabled(self): + async def fetch_async(self) -> ServiceInstance: """ - :returns: Whether to add a security warning at the end of an SMS. - :rtype: bool - """ - return self._properties['do_not_share_warning_enabled'] + Asynchronous coroutine to fetch the ServiceInstance - @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 + :returns: The fetched ServiceInstance """ - return self._properties['date_updated'] + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - @property - def url(self): - """ - :returns: The absolute URL of the resource - :rtype: unicode + async def fetch_with_http_info_async(self) -> ApiResponse: """ - return self._properties['url'] + Asynchronous coroutine to fetch the ServiceInstance and return response metadata - @property - def links(self): - """ - :returns: The URLs of related resources - :rtype: unicode - """ - return self._properties['links'] - def fetch(self): + :returns: ApiResponse with instance, status code, and headers """ - Fetch the ServiceInstance + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "Passkeys.RelyingParty.Id": passkeys_relying_party_id, + "Passkeys.RelyingParty.Name": passkeys_relying_party_name, + "Passkeys.RelyingParty.Origins": passkeys_relying_party_origins, + "Passkeys.AuthenticatorAttachment": passkeys_authenticator_attachment, + "Passkeys.DiscoverableCredentials": passkeys_discoverable_credentials, + "Passkeys.UserVerification": passkeys_user_verification, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } + ) + headers = values.of({}) - :returns: The fetched ServiceInstance - :rtype: twilio.rest.verify.v2.service.ServiceInstance - """ - return self._proxy.fetch() + headers["Content-Type"] = "application/x-www-form-urlencoded" - def delete(self): - """ - Deletes the ServiceInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - 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): + 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, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: 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 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 passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :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 """ - return self._proxy.update( + payload, _, _ = self._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, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :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 passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( friendly_name=friendly_name, code_length=code_length, lookup_enabled=lookup_enabled, @@ -567,54 +1070,1383 @@ def update(self, friendly_name=values.unset, code_length=values.unset, 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, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "Passkeys.RelyingParty.Id": passkeys_relying_party_id, + "Passkeys.RelyingParty.Name": passkeys_relying_party_name, + "Passkeys.RelyingParty.Origins": passkeys_relying_party_origins, + "Passkeys.AuthenticatorAttachment": passkeys_authenticator_attachment, + "Passkeys.DiscoverableCredentials": passkeys_discoverable_credentials, + "Passkeys.UserVerification": passkeys_user_verification, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } ) + headers = values.of({}) - @property - def verifications(self): - """ - Access the verifications + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: 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 passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured - :returns: twilio.rest.verify.v2.service.verification.VerificationList - :rtype: twilio.rest.verify.v2.service.verification.VerificationList + :returns: The updated ServiceInstance """ - return self._proxy.verifications + payload, _, _ = await self._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, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :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 passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def verification_checks(self): + def access_tokens(self) -> AccessTokenList: """ - Access the verification_checks + Access the access_tokens + """ + if self._access_tokens is None: + self._access_tokens = AccessTokenList( + self._version, + self._solution["sid"], + ) + return self._access_tokens - :returns: twilio.rest.verify.v2.service.verification_check.VerificationCheckList - :rtype: twilio.rest.verify.v2.service.verification_check.VerificationCheckList + @property + def approve_challenge(self) -> ApproveChallengeList: """ - return self._proxy.verification_checks + Access the approve_challenge + """ + if self._approve_challenge is None: + self._approve_challenge = ApproveChallengeList( + self._version, + self._solution["sid"], + ) + return self._approve_challenge + + @property + def entities(self) -> EntityList: + """ + Access the entities + """ + if self._entities is None: + self._entities = EntityList( + self._version, + self._solution["sid"], + ) + return self._entities + + @property + def messaging_configurations(self) -> MessagingConfigurationList: + """ + Access the messaging_configurations + """ + if self._messaging_configurations is None: + self._messaging_configurations = MessagingConfigurationList( + self._version, + self._solution["sid"], + ) + return self._messaging_configurations + + @property + def new_challenge(self) -> NewChallengeList: + """ + Access the new_challenge + """ + if self._new_challenge is None: + self._new_challenge = NewChallengeList( + self._version, + self._solution["sid"], + ) + return self._new_challenge + + @property + def new_factors(self) -> NewFactorList: + """ + Access the new_factors + """ + if self._new_factors is None: + self._new_factors = NewFactorList( + self._version, + self._solution["sid"], + ) + return self._new_factors @property - def rate_limits(self): + def new_verify_factors(self) -> NewVerifyFactorList: + """ + Access the new_verify_factors + """ + if self._new_verify_factors is None: + self._new_verify_factors = NewVerifyFactorList( + self._version, + self._solution["sid"], + ) + return self._new_verify_factors + + @property + def rate_limits(self) -> RateLimitList: """ Access the rate_limits + """ + if self._rate_limits is None: + self._rate_limits = RateLimitList( + self._version, + self._solution["sid"], + ) + return self._rate_limits - :returns: twilio.rest.verify.v2.service.rate_limit.RateLimitList - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitList + @property + def verifications(self) -> VerificationList: """ - return self._proxy.rate_limits + Access the verifications + """ + if self._verifications is None: + self._verifications = VerificationList( + self._version, + self._solution["sid"], + ) + return self._verifications @property - def messaging_configurations(self): + def verification_checks(self) -> VerificationCheckList: """ - Access the messaging_configurations + 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.messaging_configuration.MessagingConfigurationList - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationList + @property + def webhooks(self) -> WebhookList: """ - return self._proxy.messaging_configurations + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, + self._solution["sid"], + ) + return self._webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def _create( + self, + friendly_name: str, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "Passkeys.RelyingParty.Id": passkeys_relying_party_id, + "Passkeys.RelyingParty.Name": passkeys_relying_party_name, + "Passkeys.RelyingParty.Origins": passkeys_relying_party_origins, + "Passkeys.AuthenticatorAttachment": passkeys_authenticator_attachment, + "Passkeys.DiscoverableCredentials": passkeys_discoverable_credentials, + "Passkeys.UserVerification": passkeys_user_verification, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a security warning at the end of an SMS verification body. Disabled by default and applies only to SMS. Example SMS body: `Your AppName verification code is: 1234. Don’t share this code with anyone; our employees will never ask for the code` + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. This timestamp value is the same one as the one found in `date_created`, please use that one instead. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. Defaults to the service friendly name if not provided. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the Messaging Service containing WhatsApp Sender(s) that Verify will use to send WhatsApp messages to your users. + :param whatsapp_from: The number to use as the WhatsApp Sender that Verify will use to send WhatsApp messages to your users.This WhatsApp Sender must be associated with a Messaging Service SID. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The created ServiceInstance + """ + payload, _, _ = self._create( + 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, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + 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, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :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 passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + 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, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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, + "Passkeys.RelyingParty.Id": passkeys_relying_party_id, + "Passkeys.RelyingParty.Name": passkeys_relying_party_name, + "Passkeys.RelyingParty.Origins": passkeys_relying_party_origins, + "Passkeys.AuthenticatorAttachment": passkeys_authenticator_attachment, + "Passkeys.DiscoverableCredentials": passkeys_discoverable_credentials, + "Passkeys.UserVerification": passkeys_user_verification, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: 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 passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The created ServiceInstance + """ + payload, _, _ = await self._create_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, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + return ServiceInstance(self._version, payload) + + async def create_with_http_info_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, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :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 passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_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, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 new file mode 100644 index 0000000000..a5ecc856b6 --- /dev/null +++ b/twilio/rest/verify/v2/service/access_token.py @@ -0,0 +1,479 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AccessTokenInstance(InstanceResource): + + class FactorTypes(object): + PUSH = "push" + + """ + :ivar sid: A 34 character string that uniquely identifies this Access Token. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Verify Service. + :ivar entity_identity: The unique external identifier for the Entity of the Service. + :ivar factor_type: + :ivar factor_friendly_name: A human readable description of this factor, up to 64 characters. For a push factor, this can be the device's name. + :ivar token: The access token generated for enrollment, this is an encrypted json web token. + :ivar url: The URL of this resource. + :ivar ttl: How long, in seconds, the access token is valid. Max: 5 minutes + :ivar date_created: The date that this access token was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_identity: Optional[str] = payload.get("entity_identity") + self.factor_type: Optional["AccessTokenInstance.FactorTypes"] = payload.get( + "factor_type" + ) + self.factor_friendly_name: Optional[str] = payload.get("factor_friendly_name") + self.token: Optional[str] = payload.get("token") + self.url: Optional[str] = payload.get("url") + self.ttl: Optional[int] = deserialize.integer(payload.get("ttl")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[AccessTokenContext] = None + + @property + def _proxy(self) -> "AccessTokenContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AccessTokenContext for this AccessTokenInstance + """ + if self._context is None: + self._context = AccessTokenContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AccessTokenInstance": + """ + Fetch the AccessTokenInstance + + + :returns: The fetched AccessTokenInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AccessTokenInstance": + """ + Asynchronous coroutine to fetch the AccessTokenInstance + + + :returns: The fetched AccessTokenInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AccessTokenInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AccessTokenInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccessTokenContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the AccessTokenContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param sid: A 34 character string that uniquely identifies this Access Token. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/AccessTokens/{sid}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AccessTokenInstance: + """ + Fetch the AccessTokenInstance + + + :returns: The fetched AccessTokenInstance + """ + payload, _, _ = self._fetch() + return AccessTokenInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AccessTokenInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AccessTokenInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AccessTokenInstance: + """ + Asynchronous coroutine to fetch the AccessTokenInstance + + + :returns: The fetched AccessTokenInstance + """ + payload, _, _ = await self._fetch_async() + return AccessTokenInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AccessTokenInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AccessTokenInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 AccessTokenList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the AccessTokenList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/AccessTokens".format(**self._solution) + + def _create( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> AccessTokenInstance: + """ + Create the AccessTokenInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. + :param factor_type: + :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token + :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. + + :returns: The created AccessTokenInstance + """ + payload, _, _ = self._create( + identity=identity, + factor_type=factor_type, + factor_friendly_name=factor_friendly_name, + ttl=ttl, + ) + return AccessTokenInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Create the AccessTokenInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + factor_type=factor_type, + factor_friendly_name=factor_friendly_name, + ttl=ttl, + ) + instance = AccessTokenInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> AccessTokenInstance: + """ + Asynchronously create the AccessTokenInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. + :param factor_type: + :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token + :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. + + :returns: The created AccessTokenInstance + """ + payload, _, _ = await self._create_async( + identity=identity, + factor_type=factor_type, + factor_friendly_name=factor_friendly_name, + ttl=ttl, + ) + return AccessTokenInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the AccessTokenInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + factor_type=factor_type, + factor_friendly_name=factor_friendly_name, + ttl=ttl, + ) + instance = AccessTokenInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def get(self, sid: str) -> AccessTokenContext: + """ + Constructs a AccessTokenContext + + :param sid: A 34 character string that uniquely identifies this Access Token. + """ + return AccessTokenContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> AccessTokenContext: + """ + Constructs a AccessTokenContext + + :param sid: A 34 character string that uniquely identifies this Access Token. + """ + return AccessTokenContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/verify/v2/service/approve_challenge.py b/twilio/rest/verify/v2/service/approve_challenge.py new file mode 100644 index 0000000000..52af951f0c --- /dev/null +++ b/twilio/rest/verify/v2/service/approve_challenge.py @@ -0,0 +1,346 @@ +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 +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ApproveChallengeInstance(InstanceResource): + + class ApprovePasskeysChallengeRequest(object): + """ + :ivar id: A [base64url](https://base64.guru/standards/base64url) encoded representation of `rawId`. + :ivar raw_id: The globally unique identifier for this `PublicKeyCredential`. + :ivar authenticator_attachment: A string that indicates the mechanism by which the WebAuthn implementation is attached to the authenticator at the time the associated `navigator.credentials.create()` or `navigator.credentials.get()` call completes. + :ivar type: The valid credential types supported by the API. The values of this enumeration are used for versioning the `AuthenticatorAssertion` and `AuthenticatorAttestation` structures according to the type of the authenticator. + :ivar response: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.raw_id: Optional[str] = payload.get("rawId") + self.authenticator_attachment: Optional["ApproveChallengeInstance.str"] = ( + payload.get("authenticatorAttachment") + ) + self.type: Optional["ApproveChallengeInstance.str"] = payload.get("type") + self.response: Optional[ + ApproveChallengeList.ApprovePasskeysChallengeRequestResponse + ] = payload.get("response") + + def to_dict(self): + return { + "id": self.id, + "rawId": self.raw_id, + "authenticatorAttachment": self.authenticator_attachment, + "type": self.type, + "response": ( + self.response.to_dict() if self.response is not None else None + ), + } + + class ApprovePasskeysChallengeRequestResponse(object): + """ + :ivar authenticator_data: The [authenticator data](https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data) structure contains information from the authenticator about the processing of a credential creation or authentication request. + :ivar client_data_json: This property contains the JSON-compatible serialization of the data passed from the browser to the authenticator in order to generate this credential. + :ivar signature: An assertion signature over `authenticatorData` and `clientDataJSON`. The assertion signature is created with the private key of the key pair that was created during the originating `navigator.credentials.create()` call and verified using the public key of that same key pair. + :ivar user_handle: The user handle stored in the authenticator, specified as `user.id` in the options passed to the originating `navigator.credentials.create()` call. This property should contain a base64url-encoded entity SID. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.authenticator_data: Optional[str] = payload.get("authenticatorData") + self.client_data_json: Optional[str] = payload.get("clientDataJSON") + self.signature: Optional[str] = payload.get("signature") + self.user_handle: Optional[str] = payload.get("userHandle") + + def to_dict(self): + return { + "authenticatorData": self.authenticator_data, + "clientDataJSON": self.client_data_json, + "signature": self.signature, + "userHandle": self.user_handle, + } + + """ + :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. + :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. + :ivar status: The Status of this Challenge. One of `pending`, `expired`, `approved` or `denied`. + :ivar responded_reason: Reason for the Challenge to be in certain `status`. One of `none`, `not_needed` or `not_requested`. + :ivar details: Details provided to give context about the Challenge. + :ivar hidden_details: Details provided to give context about the Challenge. + :ivar metadata: Custom metadata associated with the challenge. + :ivar factor_type: The Factor Type of this Challenge. Currently `push` and `totp` are supported. + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Challenge. + :ivar options: An object that contains challenge options. Currently only used for `passkeys`. + """ + + 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.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["ApproveChallengeInstance.str"] = payload.get("status") + self.responded_reason: Optional["ApproveChallengeInstance.str"] = 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["ApproveChallengeInstance.str"] = payload.get( + "factor_type" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.options: Optional[Dict[str, object]] = payload.get("options") + + self._solution = { + "service_sid": service_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ApproveChallengeList(ListResource): + + class ApprovePasskeysChallengeRequest(object): + """ + :ivar id: A [base64url](https://base64.guru/standards/base64url) encoded representation of `rawId`. + :ivar raw_id: The globally unique identifier for this `PublicKeyCredential`. + :ivar authenticator_attachment: A string that indicates the mechanism by which the WebAuthn implementation is attached to the authenticator at the time the associated `navigator.credentials.create()` or `navigator.credentials.get()` call completes. + :ivar type: The valid credential types supported by the API. The values of this enumeration are used for versioning the `AuthenticatorAssertion` and `AuthenticatorAttestation` structures according to the type of the authenticator. + :ivar response: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.raw_id: Optional[str] = payload.get("rawId") + self.authenticator_attachment: Optional["ApproveChallengeInstance.str"] = ( + payload.get("authenticatorAttachment") + ) + self.type: Optional["ApproveChallengeInstance.str"] = payload.get("type") + self.response: Optional[ + ApproveChallengeList.ApprovePasskeysChallengeRequestResponse + ] = payload.get("response") + + def to_dict(self): + return { + "id": self.id, + "rawId": self.raw_id, + "authenticatorAttachment": self.authenticator_attachment, + "type": self.type, + "response": ( + self.response.to_dict() if self.response is not None else None + ), + } + + class ApprovePasskeysChallengeRequestResponse(object): + """ + :ivar authenticator_data: The [authenticator data](https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data) structure contains information from the authenticator about the processing of a credential creation or authentication request. + :ivar client_data_json: This property contains the JSON-compatible serialization of the data passed from the browser to the authenticator in order to generate this credential. + :ivar signature: An assertion signature over `authenticatorData` and `clientDataJSON`. The assertion signature is created with the private key of the key pair that was created during the originating `navigator.credentials.create()` call and verified using the public key of that same key pair. + :ivar user_handle: The user handle stored in the authenticator, specified as `user.id` in the options passed to the originating `navigator.credentials.create()` call. This property should contain a base64url-encoded entity SID. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.authenticator_data: Optional[str] = payload.get("authenticatorData") + self.client_data_json: Optional[str] = payload.get("clientDataJSON") + self.signature: Optional[str] = payload.get("signature") + self.user_handle: Optional[str] = payload.get("userHandle") + + def to_dict(self): + return { + "authenticatorData": self.authenticator_data, + "clientDataJSON": self.client_data_json, + "signature": self.signature, + "userHandle": self.user_handle, + } + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ApproveChallengeList + + :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}/Passkeys/ApproveChallenge".format( + **self._solution + ) + + def _update( + self, approve_passkeys_challenge_request: ApprovePasskeysChallengeRequest + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = approve_passkeys_challenge_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, approve_passkeys_challenge_request: ApprovePasskeysChallengeRequest + ) -> ApproveChallengeInstance: + """ + Update the ApproveChallengeInstance + + :param approve_passkeys_challenge_request: + + :returns: The updated ApproveChallengeInstance + """ + payload, _, _ = self._update( + approve_passkeys_challenge_request=approve_passkeys_challenge_request + ) + return ApproveChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def update_with_http_info( + self, approve_passkeys_challenge_request: ApprovePasskeysChallengeRequest + ) -> ApiResponse: + """ + Update the ApproveChallengeInstance and return response metadata + + :param approve_passkeys_challenge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + approve_passkeys_challenge_request=approve_passkeys_challenge_request + ) + instance = ApproveChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, approve_passkeys_challenge_request: ApprovePasskeysChallengeRequest + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = approve_passkeys_challenge_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, approve_passkeys_challenge_request: ApprovePasskeysChallengeRequest + ) -> ApproveChallengeInstance: + """ + Asynchronously update the ApproveChallengeInstance + + :param approve_passkeys_challenge_request: + + :returns: The updated ApproveChallengeInstance + """ + payload, _, _ = await self._update_async( + approve_passkeys_challenge_request=approve_passkeys_challenge_request + ) + return ApproveChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def update_with_http_info_async( + self, approve_passkeys_challenge_request: ApprovePasskeysChallengeRequest + ) -> ApiResponse: + """ + Asynchronously update the ApproveChallengeInstance and return response metadata + + :param approve_passkeys_challenge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + approve_passkeys_challenge_request=approve_passkeys_challenge_request + ) + instance = ApproveChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/verify/v2/service/entity/__init__.py b/twilio/rest/verify/v2/service/entity/__init__.py new file mode 100644 index 0000000000..f7f506f57a --- /dev/null +++ b/twilio/rest/verify/v2/service/entity/__init__.py @@ -0,0 +1,956 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.verify.v2.service.entity.challenge import ChallengeList +from twilio.rest.verify.v2.service.entity.factor import FactorList +from twilio.rest.verify.v2.service.entity.new_factor import NewFactorList + + +class EntityInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this Entity. + :ivar identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar date_created: The date that this Entity was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Entity was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Entity. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + identity: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.identity: Optional[str] = payload.get("identity") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "identity": identity or self.identity, + } + + self._context: Optional[EntityContext] = None + + @property + def _proxy(self) -> "EntityContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EntityContext for this EntityInstance + """ + if self._context is None: + self._context = EntityContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the EntityInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EntityInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EntityInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EntityInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "EntityInstance": + """ + Fetch the EntityInstance + + + :returns: The fetched EntityInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EntityInstance": + """ + Asynchronous coroutine to fetch the EntityInstance + + + :returns: The fetched EntityInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EntityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EntityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + @property + def challenges(self) -> ChallengeList: + """ + Access the challenges + """ + return self._proxy.challenges + + @property + def factors(self) -> FactorList: + """ + Access the factors + """ + return self._proxy.factors + + @property + def new_factors(self) -> NewFactorList: + """ + Access the new_factors + """ + return self._proxy.new_factors + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EntityContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, identity: str): + """ + Initialize the EntityContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + } + self._uri = "/Services/{service_sid}/Entities/{identity}".format( + **self._solution + ) + + self._challenges: Optional[ChallengeList] = None + self._factors: Optional[FactorList] = None + self._new_factors: Optional[NewFactorList] = None + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the EntityInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EntityInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EntityInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EntityInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EntityInstance: + """ + Fetch the EntityInstance + + + :returns: The fetched EntityInstance + """ + payload, _, _ = self._fetch() + return EntityInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EntityInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EntityInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> EntityInstance: + """ + Asynchronous coroutine to fetch the EntityInstance + + + :returns: The fetched EntityInstance + """ + payload, _, _ = await self._fetch_async() + return EntityInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EntityInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EntityInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def challenges(self) -> ChallengeList: + """ + Access the challenges + """ + if self._challenges is None: + self._challenges = ChallengeList( + self._version, + self._solution["service_sid"], + self._solution["identity"], + ) + return self._challenges + + @property + def factors(self) -> FactorList: + """ + Access the factors + """ + if self._factors is None: + self._factors = FactorList( + self._version, + self._solution["service_sid"], + self._solution["identity"], + ) + return self._factors + + @property + def new_factors(self) -> NewFactorList: + """ + Access the new_factors + """ + if self._new_factors is None: + self._new_factors = NewFactorList( + self._version, + self._solution["service_sid"], + self._solution["identity"], + ) + return self._new_factors + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EntityPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EntityInstance: + """ + Build an instance of EntityInstance + + :param payload: Payload response from the API + """ + + return EntityInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EntityList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the EntityList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Entities".format(**self._solution) + + def _create(self, identity: str) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, identity: str) -> EntityInstance: + """ + Create the EntityInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + :returns: The created EntityInstance + """ + payload, _, _ = self._create(identity=identity) + return EntityInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info(self, identity: str) -> ApiResponse: + """ + Create the EntityInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(identity=identity) + instance = EntityInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, identity: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, identity: str) -> EntityInstance: + """ + Asynchronously create the EntityInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + :returns: The created EntityInstance + """ + payload, _, _ = await self._create_async(identity=identity) + return EntityInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async(self, identity: str) -> ApiResponse: + """ + Asynchronously create the EntityInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(identity=identity) + instance = EntityInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EntityInstance]: + """ + Streams EntityInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EntityInstance]: + """ + Asynchronously streams EntityInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EntityInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EntityInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EntityInstance]: + """ + Lists EntityInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EntityInstance]: + """ + Asynchronously lists EntityInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EntityInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EntityInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EntityPage: + """ + Retrieve a single page of EntityInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EntityInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EntityPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EntityPage: + """ + Asynchronously retrieve a single page of EntityInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EntityInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EntityPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EntityPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EntityPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EntityPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EntityPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> EntityPage: + """ + Retrieve a specific page of EntityInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EntityInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EntityPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> EntityPage: + """ + Asynchronously retrieve a specific page of EntityInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EntityInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EntityPage(self._version, response, solution=self._solution) + + def get(self, identity: str) -> EntityContext: + """ + Constructs a EntityContext + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + """ + return EntityContext( + self._version, service_sid=self._solution["service_sid"], identity=identity + ) + + def __call__(self, identity: str) -> EntityContext: + """ + Constructs a EntityContext + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + """ + return EntityContext( + self._version, service_sid=self._solution["service_sid"], identity=identity + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/verify/v2/service/entity/challenge/__init__.py b/twilio/rest/verify/v2/service/entity/challenge/__init__.py new file mode 100644 index 0000000000..9940cbf831 --- /dev/null +++ b/twilio/rest/verify/v2/service/entity/challenge/__init__.py @@ -0,0 +1,1344 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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" + PASSKEYS = "passkeys" + + 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChallengeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChallengeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChallengeInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + auth_payload=auth_payload, + metadata=metadata, + ) + + async def update_with_http_info_async( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChallengeInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChallengeInstance: + """ + Fetch the ChallengeInstance + + + :returns: The fetched ChallengeInstance + """ + payload, _, _ = self._fetch() + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChallengeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ChallengeInstance: + """ + Asynchronous coroutine to fetch the ChallengeInstance + + + :returns: The fetched ChallengeInstance + """ + payload, _, _ = await self._fetch_async() + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChallengeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._update(auth_payload=auth_payload, metadata=metadata) + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChallengeInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + auth_payload=auth_payload, metadata=metadata + ) + instance = ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async( + auth_payload=auth_payload, metadata=metadata + ) + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChallengeInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + auth_payload=auth_payload, metadata=metadata + ) + instance = ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + factor_sid=factor_sid, + expiration_date=expiration_date, + details_message=details_message, + details_fields=details_fields, + hidden_details=hidden_details, + auth_payload=auth_payload, + ) + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ChallengeInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + factor_sid=factor_sid, + expiration_date=expiration_date, + details_message=details_message, + details_fields=details_fields, + hidden_details=hidden_details, + auth_payload=auth_payload, + ) + instance = ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + factor_sid=factor_sid, + expiration_date=expiration_date, + details_message=details_message, + details_fields=details_fields, + hidden_details=hidden_details, + auth_payload=auth_payload, + ) + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ChallengeInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + factor_sid=factor_sid, + expiration_date=expiration_date, + details_message=details_message, + details_fields=details_fields, + hidden_details=hidden_details, + auth_payload=auth_payload, + ) + instance = ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams ChallengeInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + factor_sid=factor_sid, + status=status, + order=order, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams ChallengeInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + factor_sid=factor_sid, + status=status, + order=order, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists ChallengeInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + factor_sid=factor_sid, + status=status, + order=order, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists ChallengeInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + factor_sid=factor_sid, + status=status, + order=order, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ChallengePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChallengePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ChallengePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChallengePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..4250597da6 --- /dev/null +++ b/twilio/rest/verify/v2/service/entity/challenge/notification.py @@ -0,0 +1,230 @@ +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.api_response import ApiResponse + +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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create(ttl=ttl) + return NotificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + challenge_sid=self._solution["challenge_sid"], + ) + + def create_with_http_info( + self, ttl: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Create the NotificationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(ttl=ttl) + instance = NotificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + challenge_sid=self._solution["challenge_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, ttl: Union[int, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async(ttl=ttl) + return NotificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + challenge_sid=self._solution["challenge_sid"], + ) + + async def create_with_http_info_async( + self, ttl: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the NotificationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(ttl=ttl) + instance = NotificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + challenge_sid=self._solution["challenge_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/verify/v2/service/entity/factor.py b/twilio/rest/verify/v2/service/entity/factor.py new file mode 100644 index 0000000000..823dd53f69 --- /dev/null +++ b/twilio/rest/verify/v2/service/entity/factor.py @@ -0,0 +1,1264 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class FactorInstance(InstanceResource): + + class FactorStatuses(object): + UNVERIFIED = "unverified" + VERIFIED = "verified" + + class FactorTypes(object): + PUSH = "push" + TOTP = "totp" + PASSKEYS = "passkeys" + + class TotpAlgorithms(object): + SHA1 = "sha1" + SHA256 = "sha256" + SHA512 = "sha512" + + """ + :ivar sid: A 34 character string that uniquely identifies this Factor. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar entity_sid: The unique SID identifier of the Entity. + :ivar identity: Customer unique identity for the Entity owner of the Factor. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :ivar date_created: The date that this Factor was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Factor was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar friendly_name: A human readable description of this resource, up to 64 characters. For a push factor, this can be the device's name. + :ivar status: + :ivar factor_type: + :ivar config: An object that contains configurations specific to a `factor_type`. + :ivar metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\"os\": \"Android\"}`. Can be up to 1024 characters in length. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + identity: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_sid: Optional[str] = payload.get("entity_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["FactorInstance.FactorStatuses"] = payload.get("status") + self.factor_type: Optional["FactorInstance.FactorTypes"] = payload.get( + "factor_type" + ) + self.config: Optional[Dict[str, object]] = payload.get("config") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "identity": identity, + "sid": sid or self.sid, + } + + self._context: Optional[FactorContext] = None + + @property + def _proxy(self) -> "FactorContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FactorContext for this FactorInstance + """ + if self._context is None: + self._context = FactorContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the FactorInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FactorInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FactorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FactorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "FactorInstance": + """ + Fetch the FactorInstance + + + :returns: The fetched FactorInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FactorInstance": + """ + Asynchronous coroutine to fetch the FactorInstance + + + :returns: The fetched FactorInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FactorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FactorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> "FactorInstance": + """ + Update the FactorInstance + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: The updated FactorInstance + """ + return self._proxy.update( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) + + async def update_async( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> "FactorInstance": + """ + Asynchronous coroutine to update the FactorInstance + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: The updated FactorInstance + """ + return await self._proxy.update_async( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the FactorInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FactorInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FactorContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, identity: str, sid: str): + """ + Initialize the FactorContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: Customer unique identity for the Entity owner of the Factor. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :param sid: A 34 character string that uniquely identifies this Factor. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Entities/{identity}/Factors/{sid}".format( + **self._solution + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the FactorInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FactorInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FactorInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FactorInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> FactorInstance: + """ + Fetch the FactorInstance + + + :returns: The fetched FactorInstance + """ + payload, _, _ = self._fetch() + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FactorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> FactorInstance: + """ + Asynchronous coroutine to fetch the FactorInstance + + + :returns: The fetched FactorInstance + """ + payload, _, _ = await self._fetch_async() + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FactorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> FactorInstance: + """ + Update the FactorInstance + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: The updated FactorInstance + """ + payload, _, _ = self._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, + ) + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the FactorInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> FactorInstance: + """ + Asynchronous coroutine to update the FactorInstance + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: The updated FactorInstance + """ + payload, _, _ = await self._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 FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FactorInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 FactorPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FactorInstance: + """ + Build an instance of FactorInstance + + :param payload: Payload response from the API + """ + + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class FactorList(ListResource): + + def __init__(self, version: Version, service_sid: str, identity: str): + """ + Initialize the FactorList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: Customer unique identity for the Entity owner of the Factors. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + } + self._uri = "/Services/{service_sid}/Entities/{identity}/Factors".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FactorInstance]: + """ + Streams FactorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FactorInstance]: + """ + Asynchronously streams FactorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams FactorInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams FactorInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FactorInstance]: + """ + Lists FactorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FactorInstance]: + """ + Asynchronously lists FactorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists FactorInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists FactorInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FactorPage: + """ + Retrieve a single page of FactorInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FactorInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FactorPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FactorPage: + """ + Asynchronously retrieve a single page of FactorInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FactorInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FactorPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FactorPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FactorPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FactorPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FactorPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> FactorPage: + """ + Retrieve a specific page of FactorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FactorInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FactorPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> FactorPage: + """ + Asynchronously retrieve a specific page of FactorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FactorInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FactorPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> FactorContext: + """ + Constructs a FactorContext + + :param sid: A 34 character string that uniquely identifies this Factor. + """ + return FactorContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=sid, + ) + + def __call__(self, sid: str) -> FactorContext: + """ + Constructs a FactorContext + + :param sid: A 34 character string that uniquely identifies this Factor. + """ + return FactorContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/verify/v2/service/entity/new_factor.py b/twilio/rest/verify/v2/service/entity/new_factor.py new file mode 100644 index 0000000000..79184c0e74 --- /dev/null +++ b/twilio/rest/verify/v2/service/entity/new_factor.py @@ -0,0 +1,494 @@ +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.api_response import ApiResponse + +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" + PASSKEYS = "passkeys" + + 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 options: + :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.options: Optional[Dict[str, object]] = payload.get("options") + self.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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + factor_type=factor_type, + binding_alg=binding_alg, + binding_public_key=binding_public_key, + config_app_id=config_app_id, + config_notification_platform=config_notification_platform, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + binding_secret=binding_secret, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + metadata=metadata, + ) + return NewFactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the NewFactorInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + factor_type=factor_type, + binding_alg=binding_alg, + binding_public_key=binding_public_key, + config_app_id=config_app_id, + config_notification_platform=config_notification_platform, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + binding_secret=binding_secret, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + metadata=metadata, + ) + instance = NewFactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + factor_type=factor_type, + binding_alg=binding_alg, + binding_public_key=binding_public_key, + config_app_id=config_app_id, + config_notification_platform=config_notification_platform, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + binding_secret=binding_secret, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + metadata=metadata, + ) + return NewFactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the NewFactorInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + factor_type=factor_type, + binding_alg=binding_alg, + binding_public_key=binding_public_key, + config_app_id=config_app_id, + config_notification_platform=config_notification_platform, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + binding_secret=binding_secret, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + metadata=metadata, + ) + instance = NewFactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 ded7825dfe..43920cc5b9 100644 --- a/twilio/rest/verify/v2/service/messaging_configuration.py +++ b/twilio/rest/verify/v2/service/messaging_configuration.py @@ -1,430 +1,1097 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +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") - def __init__(self, version, service_sid): + self._solution = { + "service_sid": service_sid, + "country": country or self.country, + } + + self._context: Optional[MessagingConfigurationContext] = None + + @property + def _proxy(self) -> "MessagingConfigurationContext": """ - Initialize the MessagingConfigurationList + 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: 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 - :returns: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationList - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationList + def delete(self) -> bool: """ - super(MessagingConfigurationList, self).__init__(version) + Deletes the MessagingConfigurationInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/MessagingConfigurations'.format(**self._solution) - def create(self, country, messaging_service_sid): + :returns: True if delete succeeds, False otherwise """ - Create the MessagingConfigurationInstance + return self._proxy.delete() - :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. + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessagingConfigurationInstance - :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 await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessagingConfigurationInstance with HTTP info - return MessagingConfigurationInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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 self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessagingConfigurationInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "MessagingConfigurationInstance": + """ + Fetch the MessagingConfigurationInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "MessagingConfigurationInstance": + """ + Asynchronous coroutine to fetch the MessagingConfigurationInstance - :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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of MessagingConfigurationInstance records from the API. - Request is executed immediately + Fetch the MessagingConfigurationInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of MessagingConfigurationInstance - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationPage + :returns: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessagingConfigurationInstance with HTTP info - return MessagingConfigurationPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of MessagingConfigurationInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update(self, messaging_service_sid: str) -> "MessagingConfigurationInstance": + """ + Update the MessagingConfigurationInstance - :returns: Page of MessagingConfigurationInstance - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationPage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + messaging_service_sid=messaging_service_sid, ) - return MessagingConfigurationPage(self._version, response, self._solution) + async def update_async( + self, messaging_service_sid: str + ) -> "MessagingConfigurationInstance": + """ + Asynchronous coroutine to update the MessagingConfigurationInstance + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. - def get(self, country): + :returns: The updated MessagingConfigurationInstance """ - Constructs a MessagingConfigurationContext + return await self._proxy.update_async( + messaging_service_sid=messaging_service_sid, + ) - :param country: The ISO-3166-1 country code of the country or `all`. + def update_with_http_info(self, messaging_service_sid: str) -> ApiResponse: + """ + Update the MessagingConfigurationInstance with HTTP info + + :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: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationContext - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationContext + :returns: ApiResponse with instance, status code, and headers """ - return MessagingConfigurationContext( - self._version, - service_sid=self._solution['service_sid'], - country=country, + return self._proxy.update_with_http_info( + messaging_service_sid=messaging_service_sid, ) - def __call__(self, country): + async def update_with_http_info_async( + self, messaging_service_sid: str + ) -> ApiResponse: """ - Constructs a MessagingConfigurationContext + Asynchronous coroutine to update the MessagingConfigurationInstance with HTTP info - :param country: The ISO-3166-1 country code of the country or `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: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationContext - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationContext + :returns: ApiResponse with instance, status code, and headers """ - return MessagingConfigurationContext( - self._version, - service_sid=self._solution['service_sid'], - country=country, + return await self._proxy.update_with_http_info_async( + messaging_service_sid=messaging_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 MessagingConfigurationPage(Page): - """ """ +class MessagingConfigurationContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, country: str): """ - Initialize the MessagingConfigurationPage - - :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 MessagingConfigurationContext - :returns: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationPage - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationPage + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) that the resource is associated with. + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. """ - super(MessagingConfigurationPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "service_sid": service_sid, + "country": country, + } + self._uri = "/Services/{service_sid}/MessagingConfigurations/{country}".format( + **self._solution + ) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of MessagingConfigurationInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the MessagingConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessagingConfigurationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessagingConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessagingConfigurationInstance and return response metadata + - :param dict payload: Payload response from the API + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationInstance - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessagingConfigurationInstance: + """ + Fetch the MessagingConfigurationInstance + + + :returns: The fetched MessagingConfigurationInstance + """ + payload, _, _ = self._fetch() return MessagingConfigurationInstance( self._version, payload, - service_sid=self._solution['service_sid'], + service_sid=self._solution["service_sid"], + country=self._solution["country"], ) - def __repr__(self): + def fetch_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Fetch the MessagingConfigurationInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - return '' + payload, status_code, headers = self._fetch() + instance = MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation -class MessagingConfigurationContext(InstanceContext): - """ """ + Returns: + tuple: (payload, status_code, headers) + """ - def __init__(self, version, service_sid, country): + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> MessagingConfigurationInstance: """ - Initialize the MessagingConfigurationContext + Asynchronous coroutine to fetch the MessagingConfigurationInstance + - :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`. + :returns: The fetched MessagingConfigurationInstance + """ + payload, _, _ = await self._fetch_async() + return MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) - :returns: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationContext - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationContext + async def fetch_with_http_info_async(self) -> ApiResponse: """ - super(MessagingConfigurationContext, self).__init__(version) + Asynchronous coroutine to fetch the MessagingConfigurationInstance and return response metadata - # Path Solution - self._solution = {'service_sid': service_sid, 'country': country, } - self._uri = '/Services/{service_sid}/MessagingConfigurations/{country}'.format(**self._solution) - def update(self, messaging_service_sid): + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, messaging_service_sid: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "MessagingServiceSid": messaging_service_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._update(messaging_service_sid=messaging_service_sid) + return MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def update_with_http_info(self, messaging_service_sid: str) -> ApiResponse: + """ + Update the MessagingConfigurationInstance and return response metadata - return 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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + messaging_service_sid=messaging_service_sid + ) + instance = MessagingConfigurationInstance( self._version, payload, - service_sid=self._solution['service_sid'], - country=self._solution['country'], + service_sid=self._solution["service_sid"], + country=self._solution["country"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def fetch(self): + async def _update_async(self, messaging_service_sid: str) -> tuple: """ - Fetch the MessagingConfigurationInstance + Internal async helper for update operation - :returns: The fetched MessagingConfigurationInstance - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, messaging_service_sid: str + ) -> MessagingConfigurationInstance: + """ + Asynchronous coroutine to update the MessagingConfigurationInstance + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The updated MessagingConfigurationInstance + """ + payload, _, _ = await self._update_async( + messaging_service_sid=messaging_service_sid + ) 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): + async def update_with_http_info_async( + self, messaging_service_sid: str + ) -> ApiResponse: """ - Deletes the MessagingConfigurationInstance + Asynchronous coroutine to update the MessagingConfigurationInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._update_async( + messaging_service_sid=messaging_service_sid + ) + instance = MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 MessagingConfigurationInstance(InstanceResource): - """ """ +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 __init__(self, version, payload, service_sid, country=None): + def __repr__(self) -> str: """ - Initialize the MessagingConfigurationInstance + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MessagingConfigurationList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the MessagingConfigurationList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) that the resource is associated with. - :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) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + 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'], + Create the MessagingConfigurationInstance + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The created MessagingConfigurationInstance + """ + payload, _, _ = self._create( + country=country, messaging_service_sid=messaging_service_sid + ) + return MessagingConfigurationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, country: str, messaging_service_sid: str + ) -> ApiResponse: + """ + Create the MessagingConfigurationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + country=country, messaging_service_sid=messaging_service_sid + ) + instance = MessagingConfigurationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, country: str, messaging_service_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, country: str, messaging_service_sid: str + ) -> MessagingConfigurationInstance: + """ + Asynchronously create the MessagingConfigurationInstance + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The created MessagingConfigurationInstance + """ + payload, _, _ = await self._create_async( + country=country, messaging_service_sid=messaging_service_sid + ) + return MessagingConfigurationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, country: str, messaging_service_sid: str + ) -> ApiResponse: + """ + Asynchronously create the MessagingConfigurationInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + country=country, messaging_service_sid=messaging_service_sid + ) + instance = MessagingConfigurationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessagingConfigurationInstance]: + """ + Streams MessagingConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessagingConfigurationInstance]: + """ + Asynchronously streams MessagingConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MessagingConfigurationInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MessagingConfigurationInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessagingConfigurationInstance]: + """ + Lists MessagingConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def account_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessagingConfigurationInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Asynchronously lists MessagingConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['account_sid'] - @property - def service_sid(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + Lists MessagingConfigurationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['service_sid'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MessagingConfigurationInstance and returns headers from first page - @property - def 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: ApiResponse with list of instances, status code, and headers """ - :returns: The ISO-3166-1 country code of the country or `all`. - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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['country'] + Retrieve a single page of MessagingConfigurationInstance records from the API. + Request is executed immediately - @property - def messaging_service_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 MessagingConfigurationInstance """ - :returns: The SID of the Messaging Service used for this configuration. - :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 MessagingConfigurationPage( + self._version, response, solution=self._solution + ) + + async def 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['messaging_service_sid'] + Asynchronously retrieve a single page of MessagingConfigurationInstance 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 MessagingConfigurationInstance """ - :returns: The RFC 2822 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagingConfigurationPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_created'] + Retrieve a single page with response metadata - @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: ApiResponse with MessagingConfigurationPage, status code, and headers """ - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagingConfigurationPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with MessagingConfigurationPage, status code, and headers """ - :returns: The URL of this resource. - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagingConfigurationPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> MessagingConfigurationPage: """ - return self._properties['url'] + 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 - def update(self, messaging_service_sid): + :returns: Page of MessagingConfigurationInstance """ - Update the MessagingConfigurationInstance + response = self._version.domain.twilio.request("GET", target_url) + return MessagingConfigurationPage( + self._version, response, solution=self._solution + ) - :param unicode messaging_service_sid: The SID of the Messaging Service used for this configuration. + async def get_page_async(self, target_url: str) -> MessagingConfigurationPage: + """ + Asynchronously retrieve a specific page of MessagingConfigurationInstance records from the API. + Request is executed immediately - :returns: The updated MessagingConfigurationInstance - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationInstance + :param target_url: API-generated URL for the requested results page + + :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, solution=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/new_challenge.py b/twilio/rest/verify/v2/service/new_challenge.py new file mode 100644 index 0000000000..74107dd044 --- /dev/null +++ b/twilio/rest/verify/v2/service/new_challenge.py @@ -0,0 +1,404 @@ +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 +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.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 NewChallengeInstance(InstanceResource): + + class CreatePasskeysChallengeRequest(object): + """ + :ivar identity: + :ivar factor_sid: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.identity: Optional[str] = payload.get("identity") + self.factor_sid: Optional[str] = payload.get("factor_sid") + + def to_dict(self): + return { + "identity": self.identity, + "factor_sid": self.factor_sid, + } + + """ + :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. + :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. + :ivar status: The Status of this Challenge. One of `pending`, `expired`, `approved` or `denied`. + :ivar responded_reason: Reason for the Challenge to be in certain `status`. One of `none`, `not_needed` or `not_requested`. + :ivar details: Details provided to give context about the Challenge. + :ivar hidden_details: Details provided to give context about the Challenge. + :ivar metadata: Custom metadata associated with the challenge. + :ivar factor_type: The Factor Type of this Challenge. Currently `push` and `totp` are supported. + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Challenge. + :ivar options: An object that contains challenge options. Currently only used for `passkeys`. + """ + + 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.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["ApproveChallengeInstance.str"] = payload.get("status") + self.responded_reason: Optional["ApproveChallengeInstance.str"] = 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["ApproveChallengeInstance.str"] = payload.get( + "factor_type" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.options: Optional[Dict[str, object]] = payload.get("options") + + self._solution = { + "service_sid": service_sid, + } + + self._context: Optional[NewChallengeContext] = None + + @property + def _proxy(self) -> "NewChallengeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NewChallengeContext for this NewChallengeInstance + """ + if self._context is None: + self._context = NewChallengeContext( + self._version, + service_sid=self._solution["service_sid"], + ) + return self._context + + def create( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> "NewChallengeInstance": + """ + Create the NewChallengeInstance + + :param create_passkeys_challenge_request: + + :returns: The created NewChallengeInstance + """ + return self._proxy.create( + create_passkeys_challenge_request, + ) + + async def create_async( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> "NewChallengeInstance": + """ + Asynchronous coroutine to create the NewChallengeInstance + + :param create_passkeys_challenge_request: + + :returns: The created NewChallengeInstance + """ + return await self._proxy.create_async( + create_passkeys_challenge_request, + ) + + def create_with_http_info( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> ApiResponse: + """ + Create the NewChallengeInstance with HTTP info + + :param create_passkeys_challenge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + create_passkeys_challenge_request, + ) + + async def create_with_http_info_async( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> ApiResponse: + """ + Asynchronous coroutine to create the NewChallengeInstance with HTTP info + + :param create_passkeys_challenge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + create_passkeys_challenge_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 NewChallengeContext(InstanceContext): + + class CreatePasskeysChallengeRequest(object): + """ + :ivar identity: + :ivar factor_sid: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.identity: Optional[str] = payload.get("identity") + self.factor_sid: Optional[str] = payload.get("factor_sid") + + def to_dict(self): + return { + "identity": self.identity, + "factor_sid": self.factor_sid, + } + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the NewChallengeContext + + :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}/Passkeys/Challenges".format( + **self._solution + ) + + def _create( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_passkeys_challenge_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> NewChallengeInstance: + """ + Create the NewChallengeInstance + + :param create_passkeys_challenge_request: + + :returns: The created NewChallengeInstance + """ + payload, _, _ = self._create( + create_passkeys_challenge_request=create_passkeys_challenge_request + ) + return NewChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> ApiResponse: + """ + Create the NewChallengeInstance and return response metadata + + :param create_passkeys_challenge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_passkeys_challenge_request=create_passkeys_challenge_request + ) + instance = NewChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_passkeys_challenge_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> NewChallengeInstance: + """ + Asynchronous coroutine to create the NewChallengeInstance + + :param create_passkeys_challenge_request: + + :returns: The created NewChallengeInstance + """ + payload, _, _ = await self._create_async( + create_passkeys_challenge_request=create_passkeys_challenge_request + ) + return NewChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> ApiResponse: + """ + Asynchronous coroutine to create the NewChallengeInstance and return response metadata + + :param create_passkeys_challenge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_passkeys_challenge_request=create_passkeys_challenge_request + ) + instance = NewChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 NewChallengeList(ListResource): + + class CreatePasskeysChallengeRequest(object): + """ + :ivar identity: + :ivar factor_sid: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.identity: Optional[str] = payload.get("identity") + self.factor_sid: Optional[str] = payload.get("factor_sid") + + def to_dict(self): + return { + "identity": self.identity, + "factor_sid": self.factor_sid, + } + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the NewChallengeList + + :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, + } + + def get(self) -> NewChallengeContext: + """ + Constructs a NewChallengeContext + + """ + return NewChallengeContext( + self._version, service_sid=self._solution["service_sid"] + ) + + def __call__(self) -> NewChallengeContext: + """ + Constructs a NewChallengeContext + + """ + return NewChallengeContext( + self._version, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/verify/v2/service/new_factor.py b/twilio/rest/verify/v2/service/new_factor.py new file mode 100644 index 0000000000..b5595bca5c --- /dev/null +++ b/twilio/rest/verify/v2/service/new_factor.py @@ -0,0 +1,372 @@ +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 +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NewFactorInstance(InstanceResource): + + class CreateNewPasskeysFactorRequest(object): + """ + :ivar friendly_name: + :ivar identity: + :ivar config: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.identity: Optional[str] = payload.get("identity") + self.config: Optional[ + NewFactorList.CreateNewPasskeysFactorRequestConfig + ] = payload.get("config") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "identity": self.identity, + "config": self.config.to_dict() if self.config is not None else None, + } + + class CreateNewPasskeysFactorRequestConfig(object): + """ + :ivar relying_party: + :ivar authenticator_attachment: + :ivar discoverable_credentials: + :ivar user_verification: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.relying_party: Optional[ + NewFactorList.CreateNewPasskeysFactorRequestConfigRelyingParty + ] = payload.get("relying_party") + self.authenticator_attachment: Optional["NewFactorInstance.str"] = ( + payload.get("authenticator_attachment") + ) + self.discoverable_credentials: Optional["NewFactorInstance.str"] = ( + payload.get("discoverable_credentials") + ) + self.user_verification: Optional["NewFactorInstance.str"] = payload.get( + "user_verification" + ) + + def to_dict(self): + return { + "relying_party": ( + self.relying_party.to_dict() + if self.relying_party is not None + else None + ), + "authenticator_attachment": self.authenticator_attachment, + "discoverable_credentials": self.discoverable_credentials, + "user_verification": self.user_verification, + } + + class CreateNewPasskeysFactorRequestConfigRelyingParty(object): + """ + :ivar id: + :ivar name: + :ivar origins: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.origins: Optional[List[str]] = payload.get("origins") + + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "origins": self.origins, + } + + """ + :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. + :ivar binding: Contains the `factor_type` specific secret and metadata. The Binding property is ONLY returned upon Factor creation. + :ivar options: + :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. + :ivar status: The Status of this Factor. One of `unverified` or `verified`. + :ivar factor_type: The Type of this Factor. Currently `push` and `totp` are supported. + :ivar config: An object that contains configurations specific to a `factor_type`. + :ivar metadata: Custom metadata associated with the factor. + :ivar url: The URL of this resource. + """ + + 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.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.options: Optional[Dict[str, object]] = payload.get("options") + self.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.str"] = payload.get("status") + self.factor_type: Optional["NewFactorInstance.str"] = 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, + } + + def __repr__(self) -> str: + """ + 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): + + class CreateNewPasskeysFactorRequest(object): + """ + :ivar friendly_name: + :ivar identity: + :ivar config: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.identity: Optional[str] = payload.get("identity") + self.config: Optional[ + NewFactorList.CreateNewPasskeysFactorRequestConfig + ] = payload.get("config") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "identity": self.identity, + "config": self.config.to_dict() if self.config is not None else None, + } + + class CreateNewPasskeysFactorRequestConfig(object): + """ + :ivar relying_party: + :ivar authenticator_attachment: + :ivar discoverable_credentials: + :ivar user_verification: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.relying_party: Optional[ + NewFactorList.CreateNewPasskeysFactorRequestConfigRelyingParty + ] = payload.get("relying_party") + self.authenticator_attachment: Optional["NewFactorInstance.str"] = ( + payload.get("authenticator_attachment") + ) + self.discoverable_credentials: Optional["NewFactorInstance.str"] = ( + payload.get("discoverable_credentials") + ) + self.user_verification: Optional["NewFactorInstance.str"] = payload.get( + "user_verification" + ) + + def to_dict(self): + return { + "relying_party": ( + self.relying_party.to_dict() + if self.relying_party is not None + else None + ), + "authenticator_attachment": self.authenticator_attachment, + "discoverable_credentials": self.discoverable_credentials, + "user_verification": self.user_verification, + } + + class CreateNewPasskeysFactorRequestConfigRelyingParty(object): + """ + :ivar id: + :ivar name: + :ivar origins: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.origins: Optional[List[str]] = payload.get("origins") + + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "origins": self.origins, + } + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the NewFactorList + + :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}/Passkeys/Factors".format(**self._solution) + + def _create( + self, create_new_passkeys_factor_request: CreateNewPasskeysFactorRequest + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_new_passkeys_factor_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_new_passkeys_factor_request: CreateNewPasskeysFactorRequest + ) -> NewFactorInstance: + """ + Create the NewFactorInstance + + :param create_new_passkeys_factor_request: + + :returns: The created NewFactorInstance + """ + payload, _, _ = self._create( + create_new_passkeys_factor_request=create_new_passkeys_factor_request + ) + return NewFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, create_new_passkeys_factor_request: CreateNewPasskeysFactorRequest + ) -> ApiResponse: + """ + Create the NewFactorInstance and return response metadata + + :param create_new_passkeys_factor_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_new_passkeys_factor_request=create_new_passkeys_factor_request + ) + instance = NewFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_new_passkeys_factor_request: CreateNewPasskeysFactorRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_new_passkeys_factor_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_new_passkeys_factor_request: CreateNewPasskeysFactorRequest + ) -> NewFactorInstance: + """ + Asynchronously create the NewFactorInstance + + :param create_new_passkeys_factor_request: + + :returns: The created NewFactorInstance + """ + payload, _, _ = await self._create_async( + create_new_passkeys_factor_request=create_new_passkeys_factor_request + ) + return NewFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, create_new_passkeys_factor_request: CreateNewPasskeysFactorRequest + ) -> ApiResponse: + """ + Asynchronously create the NewFactorInstance and return response metadata + + :param create_new_passkeys_factor_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_new_passkeys_factor_request=create_new_passkeys_factor_request + ) + instance = NewFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/verify/v2/service/new_verify_factor.py b/twilio/rest/verify/v2/service/new_verify_factor.py new file mode 100644 index 0000000000..703eabd3b0 --- /dev/null +++ b/twilio/rest/verify/v2/service/new_verify_factor.py @@ -0,0 +1,322 @@ +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 +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NewVerifyFactorInstance(InstanceResource): + + class VerifyPasskeysFactorRequest(object): + """ + :ivar id: A [base64url](https://base64.guru/standards/base64url) encoded representation of `rawId`. + :ivar raw_id: The globally unique identifier for this `PublicKeyCredential`. + :ivar authenticator_attachment: A string that indicates the mechanism by which the WebAuthn implementation is attached to the authenticator at the time the associated `navigator.credentials.create()` or `navigator.credentials.get()` call completes. + :ivar type: The valid credential types supported by the API. The values of this enumeration are used for versioning the `AuthenticatorAssertion` and `AuthenticatorAttestation` structures according to the type of the authenticator. + :ivar response: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.raw_id: Optional[str] = payload.get("rawId") + self.authenticator_attachment: Optional["NewVerifyFactorInstance.str"] = ( + payload.get("authenticatorAttachment") + ) + self.type: Optional["NewVerifyFactorInstance.str"] = payload.get("type") + self.response: Optional[ + NewVerifyFactorList.VerifyPasskeysFactorRequestResponse + ] = payload.get("response") + + def to_dict(self): + return { + "id": self.id, + "rawId": self.raw_id, + "authenticatorAttachment": self.authenticator_attachment, + "type": self.type, + "response": ( + self.response.to_dict() if self.response is not None else None + ), + } + + class VerifyPasskeysFactorRequestResponse(object): + """ + :ivar attestation_object: The authenticator data and an attestation statement for a new key pair generated by the authenticator. + :ivar client_data_json: This property contains the JSON-compatible serialization of the data passed from the browser to the authenticator in order to generate this credential. + :ivar transports: An array of strings providing hints as to the methods the client could use to communicate with the relevant authenticator of the public key credential to retrieve. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.attestation_object: Optional[str] = payload.get("attestationObject") + self.client_data_json: Optional[str] = payload.get("clientDataJSON") + self.transports: Optional[List[Enumstr]] = payload.get("transports") + + def to_dict(self): + return { + "attestationObject": self.attestation_object, + "clientDataJSON": self.client_data_json, + "transports": self.transports, + } + + """ + :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. + :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. + :ivar status: The Status of this Factor. One of `unverified` or `verified`. + :ivar factor_type: The Type of this Factor. Currently `push` and `totp` are supported. + :ivar config: An object that contains configurations specific to a `factor_type`. + :ivar metadata: Custom metadata associated with the factor. + :ivar url: The URL of this resource. + """ + + 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.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["NewVerifyFactorInstance.str"] = payload.get("status") + self.factor_type: Optional["NewVerifyFactorInstance.str"] = 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, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NewVerifyFactorList(ListResource): + + class VerifyPasskeysFactorRequest(object): + """ + :ivar id: A [base64url](https://base64.guru/standards/base64url) encoded representation of `rawId`. + :ivar raw_id: The globally unique identifier for this `PublicKeyCredential`. + :ivar authenticator_attachment: A string that indicates the mechanism by which the WebAuthn implementation is attached to the authenticator at the time the associated `navigator.credentials.create()` or `navigator.credentials.get()` call completes. + :ivar type: The valid credential types supported by the API. The values of this enumeration are used for versioning the `AuthenticatorAssertion` and `AuthenticatorAttestation` structures according to the type of the authenticator. + :ivar response: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.raw_id: Optional[str] = payload.get("rawId") + self.authenticator_attachment: Optional["NewVerifyFactorInstance.str"] = ( + payload.get("authenticatorAttachment") + ) + self.type: Optional["NewVerifyFactorInstance.str"] = payload.get("type") + self.response: Optional[ + NewVerifyFactorList.VerifyPasskeysFactorRequestResponse + ] = payload.get("response") + + def to_dict(self): + return { + "id": self.id, + "rawId": self.raw_id, + "authenticatorAttachment": self.authenticator_attachment, + "type": self.type, + "response": ( + self.response.to_dict() if self.response is not None else None + ), + } + + class VerifyPasskeysFactorRequestResponse(object): + """ + :ivar attestation_object: The authenticator data and an attestation statement for a new key pair generated by the authenticator. + :ivar client_data_json: This property contains the JSON-compatible serialization of the data passed from the browser to the authenticator in order to generate this credential. + :ivar transports: An array of strings providing hints as to the methods the client could use to communicate with the relevant authenticator of the public key credential to retrieve. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.attestation_object: Optional[str] = payload.get("attestationObject") + self.client_data_json: Optional[str] = payload.get("clientDataJSON") + self.transports: Optional[List[Enumstr]] = payload.get("transports") + + def to_dict(self): + return { + "attestationObject": self.attestation_object, + "clientDataJSON": self.client_data_json, + "transports": self.transports, + } + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the NewVerifyFactorList + + :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}/Passkeys/VerifyFactor".format( + **self._solution + ) + + def _update( + self, verify_passkeys_factor_request: VerifyPasskeysFactorRequest + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = verify_passkeys_factor_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, verify_passkeys_factor_request: VerifyPasskeysFactorRequest + ) -> NewVerifyFactorInstance: + """ + Update the NewVerifyFactorInstance + + :param verify_passkeys_factor_request: + + :returns: The updated NewVerifyFactorInstance + """ + payload, _, _ = self._update( + verify_passkeys_factor_request=verify_passkeys_factor_request + ) + return NewVerifyFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def update_with_http_info( + self, verify_passkeys_factor_request: VerifyPasskeysFactorRequest + ) -> ApiResponse: + """ + Update the NewVerifyFactorInstance and return response metadata + + :param verify_passkeys_factor_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + verify_passkeys_factor_request=verify_passkeys_factor_request + ) + instance = NewVerifyFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, verify_passkeys_factor_request: VerifyPasskeysFactorRequest + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = verify_passkeys_factor_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, verify_passkeys_factor_request: VerifyPasskeysFactorRequest + ) -> NewVerifyFactorInstance: + """ + Asynchronously update the NewVerifyFactorInstance + + :param verify_passkeys_factor_request: + + :returns: The updated NewVerifyFactorInstance + """ + payload, _, _ = await self._update_async( + verify_passkeys_factor_request=verify_passkeys_factor_request + ) + return NewVerifyFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def update_with_http_info_async( + self, verify_passkeys_factor_request: VerifyPasskeysFactorRequest + ) -> ApiResponse: + """ + Asynchronously update the NewVerifyFactorInstance and return response metadata + + :param verify_passkeys_factor_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + verify_passkeys_factor_request=verify_passkeys_factor_request + ) + instance = NewVerifyFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/verify/v2/service/rate_limit/__init__.py b/twilio/rest/verify/v2/service/rate_limit/__init__.py index 12177cab9f..e01a326d9e 100644 --- a/twilio/rest/verify/v2/service/rate_limit/__init__.py +++ b/twilio/rest/verify/v2/service/rate_limit/__init__.py @@ -1,462 +1,1116 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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): - """ """ +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") - def __init__(self, version, service_sid): + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[RateLimitContext] = None + + @property + def _proxy(self) -> "RateLimitContext": """ - Initialize the RateLimitList + 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: RateLimitContext for this RateLimitInstance + """ + if self._context is None: + self._context = RateLimitContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.verify.v2.service.rate_limit.RateLimitList - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitList + def delete(self) -> bool: """ - super(RateLimitList, self).__init__(version) + Deletes the RateLimitInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/RateLimits'.format(**self._solution) - def create(self, unique_name, description=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the RateLimitInstance + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RateLimitInstance - :param unicode unique_name: A unique, developer assigned name of this Rate Limit. - :param unicode description: Description of this Rate Limit - :returns: The created RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'UniqueName': unique_name, 'Description': description, }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RateLimitInstance with HTTP info - return RateLimitInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - 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. + return self._proxy.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RateLimitInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.verify.v2.service.rate_limit.RateLimitInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_with_http_info_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "RateLimitInstance": + """ + Fetch the RateLimitInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "RateLimitInstance": + """ + Asynchronous coroutine to fetch the RateLimitInstance - :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 await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of RateLimitInstance records from the API. - Request is executed immediately + Fetch the RateLimitInstance with HTTP info - :param str page_token: PageToken provided by the API - :param int page_number: 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: ApiResponse with instance, status code, and headers """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RateLimitInstance with HTTP info - return RateLimitPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of RateLimitInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, description: Union[str, object] = values.unset + ) -> "RateLimitInstance": + """ + Update the RateLimitInstance - :returns: Page of RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitPage + :param description: Description of this Rate Limit + + :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) + async def update_async( + self, description: Union[str, object] = values.unset + ) -> "RateLimitInstance": + """ + Asynchronous coroutine to update the RateLimitInstance + + :param description: Description of this Rate Limit - def get(self, sid): + :returns: The updated RateLimitInstance """ - Constructs a RateLimitContext + return await self._proxy.update_async( + description=description, + ) + + def update_with_http_info( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the RateLimitInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return RateLimitContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update_with_http_info( + description=description, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: """ - Constructs a RateLimitContext + Asynchronous coroutine to update the RateLimitInstance with HTTP info + + :param description: Description of this Rate Limit - :param sid: The unique string that identifies the resource + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + description=description, + ) - :returns: twilio.rest.verify.v2.service.rate_limit.RateLimitContext - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitContext + @property + def buckets(self) -> BucketList: """ - return RateLimitContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Access the buckets + """ + 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) -> tuple: """ - Build an instance of RateLimitInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance + def delete(self) -> bool: """ - return RateLimitInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the RateLimitInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the RateLimitInstance and return response metadata -class RateLimitContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, service_sid, sid): + async def _delete_async(self) -> tuple: """ - Initialize the RateLimitContext + Internal async helper for delete operation - :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: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.verify.v2.service.rate_limit.RateLimitContext - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitContext + async def delete_async(self) -> bool: """ - super(RateLimitContext, self).__init__(version) + Asynchronous coroutine that deletes the RateLimitInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/RateLimits/{sid}'.format(**self._solution) - # Dependents - self._buckets = None + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RateLimitInstance and return response metadata + - def update(self, description=values.unset): + :returns: ApiResponse with success boolean, status code, and headers """ - Update the RateLimitInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :param unicode description: Description of this Rate Limit + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The updated RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of({'Description': description, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RateLimitInstance: + """ + Fetch the RateLimitInstance + + :returns: The fetched RateLimitInstance + """ + payload, _, _ = self._fetch() 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 fetch_with_http_info(self) -> ApiResponse: """ - Fetch the RateLimitInstance + Fetch the RateLimitInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RateLimitInstance: + """ + Asynchronous coroutine to fetch the RateLimitInstance + :returns: The fetched RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = await self._fetch_async() + return RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RateLimitInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, description: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( + { + "Description": description, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, description: Union[str, object] = values.unset + ) -> RateLimitInstance: + """ + Update the RateLimitInstance + + :param description: Description of this Rate Limit + + :returns: The updated RateLimitInstance + """ + payload, _, _ = self._update(description=description) 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): + def update_with_http_info( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: """ - Deletes the RateLimitInstance + Update the RateLimitInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param description: Description of this Rate Limit + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(description=description) + instance = RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, description: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Description": description, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, description: Union[str, object] = values.unset + ) -> RateLimitInstance: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Asynchronous coroutine to update the RateLimitInstance + + :param description: Description of this Rate Limit + + :returns: The updated RateLimitInstance + """ + payload, _, _ = await self._update_async(description=description) + return RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RateLimitInstance and return response metadata + + :param description: Description of this Rate Limit + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + description=description + ) + instance = RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @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'), + return RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RateLimitList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the RateLimitList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/RateLimits".format(**self._solution) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def _create( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation - @property - def _proxy(self): + Returns: + tuple: (payload, status_code, headers) """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: RateLimitContext for this RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitContext + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> RateLimitInstance: """ - if self._context is None: - self._context = RateLimitContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the RateLimitInstance - @property - def sid(self): + :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 """ - :returns: A string that uniquely identifies this Rate Limit. - :rtype: unicode + payload, _, _ = self._create(unique_name=unique_name, description=description) + return RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> ApiResponse: """ - return self._properties['sid'] + Create the RateLimitInstance and return response metadata - @property - def service_sid(self): + :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: ApiResponse with instance, status code, and headers """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + payload, status_code, headers = self._create( + unique_name=unique_name, description=description + ) + instance = RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> tuple: """ - return self._properties['service_sid'] + Internal async helper for create operation - @property - def account_sid(self): + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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'] + payload, _, _ = await self._create_async( + unique_name=unique_name, description=description + ) + return RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def unique_name(self): + async def create_with_http_info_async( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> ApiResponse: """ - :returns: A unique, developer assigned name of this Rate Limit. - :rtype: unicode + Asynchronously create the RateLimitInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['unique_name'] + payload, status_code, headers = await self._create_async( + unique_name=unique_name, description=description + ) + instance = RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def description(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RateLimitInstance]: """ - :returns: Description 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['description'] + 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[RateLimitInstance]: """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + 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['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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + Streams RateLimitInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def url(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The URL of this resource. - :rtype: unicode + Asynchronously streams RateLimitInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['url'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def links(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RateLimitInstance]: """ - :returns: The URLs of related resources - :rtype: unicode + 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['links'] - def update(self, description=values.unset): + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RateLimitInstance]: """ - Update the RateLimitInstance + Asynchronously lists RateLimitInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :param unicode description: Description of this Rate Limit + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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 RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance + :returns: list that will contain up to limit results """ - return self._proxy.update(description=description, ) - def fetch(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Fetch the RateLimitInstance + Lists RateLimitInstance and returns headers from first page - :returns: The fetched RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._proxy.fetch() + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - def delete(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Deletes the RateLimitInstance + Asynchronously lists RateLimitInstance and returns headers from first page - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._proxy.delete() + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def buckets(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: """ - Access the buckets + 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: twilio.rest.verify.v2.service.rate_limit.bucket.BucketList - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketList + :returns: Page of RateLimitInstance """ - return self._proxy.buckets + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RateLimitPage: + """ + Asynchronously retrieve a single page of RateLimitInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RateLimitInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RateLimitPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RateLimitPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RateLimitPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RateLimitPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RateLimitPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> RateLimitPage: + """ + Retrieve a specific page of RateLimitInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RateLimitInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RateLimitPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> RateLimitPage: + """ + Asynchronously retrieve a specific page of RateLimitInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RateLimitInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RateLimitPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> RateLimitContext: + """ + Constructs a RateLimitContext + + :param sid: The Twilio-provided string that uniquely identifies the Rate Limit resource to fetch. + """ + return RateLimitContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RateLimitContext: + """ + Constructs a RateLimitContext + + :param sid: The Twilio-provided string that uniquely identifies the Rate Limit resource to fetch. + """ + return RateLimitContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 4e66302f27..9b47a70c3c 100644 --- a/twilio/rest/verify/v2/service/rate_limit/bucket.py +++ b/twilio/rest/verify/v2/service/rate_limit/bucket.py @@ -1,464 +1,1159 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +class BucketInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this Bucket. + :ivar rate_limit_sid: The Twilio-provided string that uniquely identifies the Rate Limit resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Rate Limit resource. + :ivar max: Maximum number of requests permitted in during the interval. + :ivar interval: Number of seconds that the rate limit will be enforced over. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + rate_limit_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.rate_limit_sid: Optional[str] = payload.get("rate_limit_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.max: Optional[int] = deserialize.integer(payload.get("max")) + self.interval: Optional[int] = deserialize.integer(payload.get("interval")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "rate_limit_sid": rate_limit_sid, + "sid": sid or self.sid, + } - def __init__(self, version, service_sid, rate_limit_sid): + self._context: Optional[BucketContext] = None + + @property + def _proxy(self) -> "BucketContext": """ - Initialize the BucketList + 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 rate_limit_sid: Rate Limit Sid. + :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 - :returns: twilio.rest.verify.v2.service.rate_limit.bucket.BucketList - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketList + def delete(self) -> bool: """ - super(BucketList, self).__init__(version) + Deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BucketInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BucketInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "BucketInstance": + """ + Fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BucketInstance": + """ + Asynchronous coroutine to fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BucketInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BucketInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> "BucketInstance": + """ + Update the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The updated BucketInstance + """ + return self._proxy.update( + max=max, + interval=interval, + ) + + async def update_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> "BucketInstance": + """ + Asynchronous coroutine to update the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The updated BucketInstance + """ + return await self._proxy.update_async( + max=max, + interval=interval, + ) + + def update_with_http_info( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the BucketInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + max=max, + interval=interval, + ) + + async def update_with_http_info_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BucketInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + max=max, + interval=interval, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BucketContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, rate_limit_sid: str, sid: str + ): + """ + Initialize the BucketContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :param rate_limit_sid: The Twilio-provided string that uniquely identifies the Rate Limit resource. + :param sid: A 34 character string that uniquely identifies this Bucket. + """ + super().__init__(version) # Path Solution - self._solution = {'service_sid': service_sid, 'rate_limit_sid': rate_limit_sid, } - self._uri = '/Services/{service_sid}/RateLimits/{rate_limit_sid}/Buckets'.format(**self._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 create(self, max, interval): + def _delete(self) -> tuple: """ - Create the BucketInstance + Internal helper for delete operation - :param unicode max: Max number of requests. - :param unicode interval: Number of seconds that the rate limit will be enforced over. + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: The created BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketInstance + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BucketInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - data = values.of({'Max': max, 'Interval': interval, }) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + headers = values.of({}) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BucketInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BucketInstance: + """ + Fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + payload, _, _ = self._fetch() 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 stream(self, limit=None, page_size=None): + def fetch_with_http_info(self) -> ApiResponse: """ - 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. + Fetch the BucketInstance and return response metadata - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit 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: ApiResponse with instance, status code, and headers """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) + payload, status_code, headers = self._fetch() + instance = BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - return self._version.stream(page, limits['limit'], limits['page_limit']) + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - def list(self, limit=None, page_size=None): + Returns: + tuple: (payload, status_code, headers) """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + headers = values.of({}) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.verify.v2.service.rate_limit.bucket.BucketInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) + headers["Accept"] = "application/json" - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> BucketInstance: """ - Retrieve a single page of BucketInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch 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 - :returns: Page of BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketPage + :returns: The fetched BucketInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + payload, _, _ = await self._fetch_async() + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BucketInstance and return response metadata - return BucketPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of BucketInstance records from the API. - Request is executed immediately + payload, status_code, headers = await self._fetch_async() + instance = BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param str target_url: API-generated URL for the requested results page + def _update( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation - :returns: Page of BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketPage + Returns: + tuple: (payload, status_code, headers) """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + + data = values.of( + { + "Max": max, + "Interval": interval, + } ) + headers = values.of({}) - return BucketPage(self._version, response, self._solution) + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - def get(self, sid): + def update( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> BucketInstance: """ - Constructs a BucketContext + Update the BucketInstance - :param sid: A string that uniquely identifies this Bucket. + :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: twilio.rest.verify.v2.service.rate_limit.bucket.BucketContext - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketContext + :returns: The updated BucketInstance """ - return BucketContext( + payload, _, _ = self._update(max=max, interval=interval) + return BucketInstance( self._version, - service_sid=self._solution['service_sid'], - rate_limit_sid=self._solution['rate_limit_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + def update_with_http_info( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Constructs a BucketContext + Update the BucketInstance and return response metadata - :param sid: A string that uniquely identifies this Bucket. + :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: twilio.rest.verify.v2.service.rate_limit.bucket.BucketContext - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketContext + :returns: ApiResponse with instance, status code, and headers """ - return BucketContext( + payload, status_code, headers = self._update(max=max, interval=interval) + instance = BucketInstance( self._version, - service_sid=self._solution['service_sid'], - rate_limit_sid=self._solution['rate_limit_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _update_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> tuple: """ - Provide a friendly representation + Internal async helper for update operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + data = values.of( + { + "Max": max, + "Interval": interval, + } + ) + headers = values.of({}) -class BucketPage(Page): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, response, solution): + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> BucketInstance: """ - Initialize the BucketPage + Asynchronous coroutine to update 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. + :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: twilio.rest.verify.v2.service.rate_limit.bucket.BucketPage - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketPage + :returns: The updated BucketInstance """ - super(BucketPage, self).__init__(version, response) + payload, _, _ = await self._update_async(max=max, interval=interval) + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) - # Path Solution - self._solution = solution + async def update_with_http_info_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BucketInstance and return response metadata + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. - def get_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of BucketInstance + payload, status_code, headers = await self._update_async( + max=max, interval=interval + ) + instance = BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 BucketPage(Page): - :param dict payload: Payload response from the API + def get_instance(self, payload: Dict[str, Any]) -> BucketInstance: + """ + Build an instance of BucketInstance - :returns: twilio.rest.verify.v2.service.rate_limit.bucket.BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.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'], + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class BucketContext(InstanceContext): - """ """ +class BucketList(ListResource): - def __init__(self, version, service_sid, rate_limit_sid, sid): + def __init__(self, version: Version, service_sid: str, rate_limit_sid: str): """ - Initialize the BucketContext + Initialize the BucketList - :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. + :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. - :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) + 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) + self._solution = { + "service_sid": service_sid, + "rate_limit_sid": rate_limit_sid, + } + self._uri = ( + "/Services/{service_sid}/RateLimits/{rate_limit_sid}/Buckets".format( + **self._solution + ) + ) - def update(self, max=values.unset, interval=values.unset): + def _create(self, max: int, interval: int) -> tuple: """ - Update the BucketInstance + Internal helper for create operation - :param unicode max: Max number of requests. - :param unicode interval: Number of seconds that the rate limit will be enforced over. + Returns: + tuple: (payload, status_code, headers) + """ - :returns: The updated BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketInstance + data = values.of( + { + "Max": max, + "Interval": interval, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, max: int, interval: int) -> BucketInstance: """ - data = values.of({'Max': max, 'Interval': interval, }) + Create the BucketInstance - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + :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 + """ + payload, _, _ = self._create(max=max, interval=interval) 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"], ) - def fetch(self): + def create_with_http_info(self, max: int, interval: int) -> ApiResponse: """ - Fetch the BucketInstance + Create the BucketInstance and return response metadata - :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(max=max, interval=interval) + instance = BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, max: int, interval: int) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, max: int, interval: int) -> BucketInstance: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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 + """ + payload, _, _ = await self._create_async(max=max, interval=interval) 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"], ) - def delete(self): + async def create_with_http_info_async(self, max: int, interval: int) -> ApiResponse: """ - Deletes the BucketInstance + Asynchronously create the BucketInstance and return response metadata - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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: ApiResponse with instance, status code, and headers """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload, status_code, headers = await self._create_async( + max=max, interval=interval + ) + instance = BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BucketInstance]: """ - Provide a friendly representation + 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. - :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 BucketInstance(InstanceResource): - """ """ + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BucketInstance]: + """ + Asynchronously streams BucketInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def __init__(self, version, payload, service_sid, rate_limit_sid, sid=None): + :returns: Generator that will yield up to limit results """ - Initialize the BucketInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :returns: twilio.rest.verify.v2.service.rate_limit.bucket.BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketInstance + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - super(BucketInstance, self).__init__(version) + Streams BucketInstance and returns headers from first page - # 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'), - } - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'rate_limit_sid': rate_limit_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: tuple of (generator, status_code, headers) where generator yields instances """ - 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_response = self.page_with_http_info(page_size=limits["page_size"]) - :returns: BucketContext for this BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketContext + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - 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 + Asynchronously streams BucketInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: A string that uniquely identifies this Bucket. - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BucketInstance]: """ - return self._properties['sid'] + Lists BucketInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def rate_limit_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: Rate Limit Sid. - :rtype: unicode + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BucketInstance]: """ - return self._properties['rate_limit_sid'] + 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. - @property - def 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 Service that the resource is associated with - :rtype: unicode + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['service_sid'] + Lists BucketInstance and returns headers from first page - @property - def account_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: ApiResponse with list of instances, status code, and headers """ - :returns: The SID of the Account that created the resource - :rtype: unicode + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return self._properties['account_sid'] + Asynchronously lists BucketInstance and returns headers from first page - @property - def max(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: ApiResponse with list of instances, status code, and headers """ - :returns: Max number of requests. - :rtype: unicode + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['max'] + Retrieve a single page of BucketInstance records from the API. + Request is executed immediately - @property - def interval(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 BucketInstance """ - :returns: Number of seconds that the rate limit will be enforced over. - :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 BucketPage(self._version, response, solution=self._solution) + + async def 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: """ - return self._properties['interval'] + Asynchronously retrieve a single page of BucketInstance 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 BucketInstance """ - :returns: The RFC 2822 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BucketPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_created'] + Retrieve a single page with response metadata - @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: ApiResponse with BucketPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BucketPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BucketPage, status code, and headers """ - 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BucketPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..88ae5cb750 100644 --- a/twilio/rest/verify/v2/service/verification.py +++ b/twilio/rest/verify/v2/service/verification.py @@ -1,417 +1,903 @@ -# 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.api_response import ApiResponse 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" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with + class RiskCheck(object): + ENABLE = "enable" + DISABLE = "disable" - :returns: twilio.rest.verify.v2.service.verification.VerificationList - :rtype: twilio.rest.verify.v2.service.verification.VerificationList - """ - super(VerificationList, self).__init__(version) + class Status(object): + CANCELED = "canceled" + APPROVED = "approved" - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Verifications'.format(**self._solution) + """ + :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 - 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): + @property + def _proxy(self) -> "VerificationContext": """ - Create the VerificationInstance + 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: 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: 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 - :returns: The created VerificationInstance - :rtype: twilio.rest.verify.v2.service.verification.VerificationInstance + def fetch(self) -> "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, - }) + Fetch the VerificationInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return VerificationInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + :returns: The fetched VerificationInstance + """ + return self._proxy.fetch() - def get(self, sid): + async def fetch_async(self) -> "VerificationInstance": """ - Constructs a VerificationContext + Asynchronous coroutine to fetch the VerificationInstance - :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 """ - return VerificationContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.fetch_async() - def __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a VerificationContext + Fetch the VerificationInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return VerificationContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.fetch_with_http_info() - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the VerificationInstance with HTTP info - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update(self, status: "VerificationInstance.Status") -> "VerificationInstance": """ - return '' + Update the VerificationInstance + :param status: -class VerificationPage(Page): - """ """ + :returns: The updated VerificationInstance + """ + return self._proxy.update( + status=status, + ) - def __init__(self, version, response, solution): + async def update_async( + self, status: "VerificationInstance.Status" + ) -> "VerificationInstance": """ - Initialize the VerificationPage + Asynchronous coroutine to update the VerificationInstance - :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 status: - :returns: twilio.rest.verify.v2.service.verification.VerificationPage - :rtype: twilio.rest.verify.v2.service.verification.VerificationPage + :returns: The updated VerificationInstance """ - super(VerificationPage, self).__init__(version, response) + return await self._proxy.update_async( + status=status, + ) - # Path Solution - self._solution = solution + def update_with_http_info( + self, status: "VerificationInstance.Status" + ) -> ApiResponse: + """ + Update the VerificationInstance with HTTP info + + :param status: - def get_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of VerificationInstance + return self._proxy.update_with_http_info( + status=status, + ) - :param dict payload: Payload response from the API + async def update_with_http_info_async( + self, status: "VerificationInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the VerificationInstance with HTTP info + + :param status: - :returns: twilio.rest.verify.v2.service.verification.VerificationInstance - :rtype: twilio.rest.verify.v2.service.verification.VerificationInstance + :returns: ApiResponse with instance, status code, and headers """ - return VerificationInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + return await self._proxy.update_with_http_info_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 VerificationContext(InstanceContext): - """ """ - def __init__(self, version, service_sid, sid): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the VerificationContext - :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 + :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(VerificationContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Verifications/{sid}'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Verifications/{sid}".format( + **self._solution + ) - def update(self, status): + def _fetch(self) -> tuple: """ - Update the VerificationInstance + Internal helper for fetch operation - :param VerificationInstance.Status status: The new status of the resource - - :returns: The updated VerificationInstance - :rtype: twilio.rest.verify.v2.service.verification.VerificationInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of({'Status': status, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers = values.of({}) - return VerificationInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) - def fetch(self): + def fetch(self) -> VerificationInstance: """ Fetch the VerificationInstance + :returns: The fetched VerificationInstance - :rtype: twilio.rest.verify.v2.service.verification.VerificationInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - + payload, _, _ = self._fetch() 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 fetch_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Fetch the VerificationInstance and return response metadata - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) -class VerificationInstance(InstanceResource): - """ """ + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - class Channel(object): - SMS = "sms" - CALL = "call" - EMAIL = "email" + Returns: + tuple: (payload, status_code, headers) + """ - class Status(object): - CANCELED = "canceled" - APPROVED = "approved" + headers = values.of({}) - 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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - @property - def _proxy(self): + async def fetch_async(self) -> VerificationInstance: """ - 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 fetch the VerificationInstance - :returns: VerificationContext for this VerificationInstance - :rtype: twilio.rest.verify.v2.service.verification.VerificationContext - """ - if self._context is None: - self._context = VerificationContext( - 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 resource - :rtype: unicode + :returns: The fetched VerificationInstance """ - return self._properties['sid'] + payload, _, _ = await self._fetch_async() + return VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + async def fetch_with_http_info_async(self) -> ApiResponse: """ - return self._properties['service_sid'] + Asynchronous coroutine to fetch the VerificationInstance and return response metadata - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def to(self): - """ - :returns: The phone number or email being verified - :rtype: unicode + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['to'] + payload, status_code, headers = await self._fetch_async() + instance = VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def channel(self): - """ - :returns: The verification method used. - :rtype: VerificationInstance.Channel + def _update(self, status: "VerificationInstance.Status") -> tuple: """ - return self._properties['channel'] + Internal helper for update operation - @property - def status(self): - """ - :returns: The status of the verification resource - :rtype: unicode + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['status'] - @property - def valid(self): + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, status: "VerificationInstance.Status") -> VerificationInstance: """ - :returns: Whether the verification was successful - :rtype: bool + Update the VerificationInstance + + :param status: + + :returns: The updated VerificationInstance """ - return self._properties['valid'] + payload, _, _ = self._update(status=status) + return VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - @property - def lookup(self): + def update_with_http_info( + self, status: "VerificationInstance.Status" + ) -> ApiResponse: """ - :returns: Information about the phone number being verified - :rtype: dict + Update the VerificationInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['lookup'] + payload, status_code, headers = self._update(status=status) + instance = VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def amount(self): + async def _update_async(self, status: "VerificationInstance.Status") -> tuple: """ - :returns: The amount of the associated PSD2 compliant transaction. - :rtype: unicode + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['amount'] - @property - def payee(self): + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, status: "VerificationInstance.Status" + ) -> VerificationInstance: """ - :returns: The payee of the associated PSD2 compliant transaction - :rtype: unicode + Asynchronous coroutine to update the VerificationInstance + + :param status: + + :returns: The updated VerificationInstance """ - return self._properties['payee'] + payload, _, _ = await self._update_async(status=status) + return VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - @property - def send_code_attempts(self): + async def update_with_http_info_async( + self, status: "VerificationInstance.Status" + ) -> ApiResponse: """ - :returns: An array of verification attempt objects. - :rtype: dict + Asynchronous coroutine to update the VerificationInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['send_code_attempts'] + payload, status_code, headers = await self._update_async(status=status) + instance = VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def date_created(self): + def __repr__(self) -> str: """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + Provide a friendly representation + + :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): + +class VerificationList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + Initialize the VerificationList + + :param version: Version that contains the resource + :param service_sid: The SID of the verification [Service](https://www.twilio.com/docs/verify/api/service) to create the resource under. + """ - return self._properties['date_updated'] + super().__init__(version) - @property - def url(self): + # 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "To": to, + "Channel": channel, + "CustomFriendlyName": custom_friendly_name, + "CustomMessage": custom_message, + "SendDigits": send_digits, + "Locale": locale, + "CustomCode": custom_code, + "Amount": amount, + "Payee": payee, + "RateLimits": serialize.object(rate_limits), + "ChannelConfiguration": serialize.object(channel_configuration), + "AppHash": app_hash, + "TemplateSid": template_sid, + "TemplateCustomSubstitutions": template_custom_substitutions, + "DeviceIp": device_ip, + "EnableSnaClientToken": serialize.boolean_to_string( + enable_sna_client_token + ), + "RiskCheck": risk_check, + "Tags": tags, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - :returns: The absolute URL of the Verification resource - :rtype: unicode + 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 [DEPRECATED]. + :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 tags will also be included as part of the verification and message status event type payloads. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. **This value should not contain PII.** + + :returns: The created VerificationInstance """ - return self._properties['url'] + payload, _, _ = self._create( + to=to, + channel=channel, + custom_friendly_name=custom_friendly_name, + custom_message=custom_message, + send_digits=send_digits, + locale=locale, + custom_code=custom_code, + amount=amount, + payee=payee, + rate_limits=rate_limits, + channel_configuration=channel_configuration, + app_hash=app_hash, + template_sid=template_sid, + template_custom_substitutions=template_custom_substitutions, + device_ip=device_ip, + enable_sna_client_token=enable_sna_client_token, + risk_check=risk_check, + tags=tags, + ) + return VerificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - def update(self, status): + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the VerificationInstance and return response metadata + + :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 [DEPRECATED]. + :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 tags will also be included as part of the verification and message status event type payloads. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. **This value should not contain PII.** + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + to=to, + channel=channel, + custom_friendly_name=custom_friendly_name, + custom_message=custom_message, + send_digits=send_digits, + locale=locale, + custom_code=custom_code, + amount=amount, + payee=payee, + rate_limits=rate_limits, + channel_configuration=channel_configuration, + app_hash=app_hash, + template_sid=template_sid, + template_custom_substitutions=template_custom_substitutions, + device_ip=device_ip, + enable_sna_client_token=enable_sna_client_token, + risk_check=risk_check, + tags=tags, + ) + instance = VerificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "To": to, + "Channel": channel, + "CustomFriendlyName": custom_friendly_name, + "CustomMessage": custom_message, + "SendDigits": send_digits, + "Locale": locale, + "CustomCode": custom_code, + "Amount": amount, + "Payee": payee, + "RateLimits": serialize.object(rate_limits), + "ChannelConfiguration": serialize.object(channel_configuration), + "AppHash": app_hash, + "TemplateSid": template_sid, + "TemplateCustomSubstitutions": template_custom_substitutions, + "DeviceIp": device_ip, + "EnableSnaClientToken": serialize.boolean_to_string( + enable_sna_client_token + ), + "RiskCheck": risk_check, + "Tags": tags, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 [DEPRECATED]. + :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 tags will also be included as part of the verification and message status event type payloads. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. **This value should not contain PII.** + + :returns: The created VerificationInstance """ - Update the VerificationInstance + payload, _, _ = await self._create_async( + to=to, + channel=channel, + custom_friendly_name=custom_friendly_name, + custom_message=custom_message, + send_digits=send_digits, + locale=locale, + custom_code=custom_code, + amount=amount, + payee=payee, + rate_limits=rate_limits, + channel_configuration=channel_configuration, + app_hash=app_hash, + template_sid=template_sid, + template_custom_substitutions=template_custom_substitutions, + device_ip=device_ip, + enable_sna_client_token=enable_sna_client_token, + risk_check=risk_check, + tags=tags, + ) + return VerificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - :param VerificationInstance.Status status: The new status of the resource + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the VerificationInstance and return response metadata + + :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 [DEPRECATED]. + :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 tags will also be included as part of the verification and message status event type payloads. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. **This value should not contain PII.** + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + to=to, + channel=channel, + custom_friendly_name=custom_friendly_name, + custom_message=custom_message, + send_digits=send_digits, + locale=locale, + custom_code=custom_code, + amount=amount, + payee=payee, + rate_limits=rate_limits, + channel_configuration=channel_configuration, + app_hash=app_hash, + template_sid=template_sid, + template_custom_substitutions=template_custom_substitutions, + device_ip=device_ip, + enable_sna_client_token=enable_sna_client_token, + risk_check=risk_check, + tags=tags, + ) + instance = VerificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: The updated VerificationInstance - :rtype: twilio.rest.verify.v2.service.verification.VerificationInstance + def get(self, sid: str) -> VerificationContext: """ - return self._proxy.update(status, ) + Constructs a VerificationContext - def fetch(self): + :param sid: The Twilio-provided string that uniquely identifies the Verification resource to update. """ - Fetch the VerificationInstance + return VerificationContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - :returns: The fetched VerificationInstance - :rtype: twilio.rest.verify.v2.service.verification.VerificationInstance + def __call__(self, sid: str) -> VerificationContext: """ - return self._proxy.fetch() + Constructs a VerificationContext + + :param sid: The Twilio-provided string that uniquely identifies the Verification resource to update. + """ + return VerificationContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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..b80c8d6d46 100644 --- a/twilio/rest/verify/v2/service/verification_check.py +++ b/twilio/rest/verify/v2/service/verification_check.py @@ -1,242 +1,317 @@ -# 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 - - :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.verify.v2.service.verification_check.VerificationCheckList - :rtype: twilio.rest.verify.v2.service.verification_check.VerificationCheckList - """ - super(VerificationCheckList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/VerificationCheck'.format(**self._solution) - - def create(self, code, to=values.unset, 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 - - :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, ) - - return VerificationCheckInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class VerificationCheckPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the VerificationCheckPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with - - :returns: twilio.rest.verify.v2.service.verification_check.VerificationCheckPage - :rtype: twilio.rest.verify.v2.service.verification_check.VerificationCheckPage - """ - super(VerificationCheckPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of VerificationCheckInstance + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - :param dict payload: Payload response from the API + Twilio - Verify + This is the public Twilio REST 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'], ) + 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, values +from twilio.base.api_response import ApiResponse - :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 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')), + 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, } - # Context - self._context = None - self._solution = {'service_sid': 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 Service that the resource is associated with - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['service_sid'] + 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 to(self): - """ - :returns: The phone number or email being verified - :rtype: unicode - """ - return self._properties['to'] +class VerificationCheckList(ListResource): - @property - def channel(self): - """ - :returns: The verification method to use - :rtype: VerificationCheckInstance.Channel + def __init__(self, version: Version, service_sid: str): """ - return self._properties['channel'] + Initialize the VerificationCheckList - @property - def status(self): - """ - :returns: The status of the verification resource - :rtype: unicode - """ - return self._properties['status'] + :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 valid(self): """ - :returns: Whether the verification was successful - :rtype: bool - """ - return self._properties['valid'] + super().__init__(version) - @property - def amount(self): - """ - :returns: The amount of the associated PSD2 compliant transaction. - :rtype: unicode + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/VerificationCheck".format(**self._solution) + + def _create( + self, + code: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + sna_client_token: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['amount'] + Create the VerificationCheckInstance - @property - def payee(self): - """ - :returns: The payee of the associated PSD2 compliant transaction - :rtype: unicode - """ - return self._properties['payee'] + :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 date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the Verification Check resource was created - :rtype: datetime + :returns: The created VerificationCheckInstance """ - return self._properties['date_created'] + payload, _, _ = self._create( + code=code, + to=to, + verification_sid=verification_sid, + amount=amount, + payee=payee, + sna_client_token=sna_client_token, + ) + return VerificationCheckInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the VerificationCheckInstance and return response metadata + + :param code: The 4-10 character string being verified. + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param verification_sid: A SID that uniquely identifies the Verification Check. Either this parameter or the `to` phone number/[email](https://www.twilio.com/docs/verify/email) must be specified. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param sna_client_token: A sna client token received in sna url invocation response needs to be passed in Verification Check request and should match to get successful response. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + code=code, + to=to, + verification_sid=verification_sid, + amount=amount, + payee=payee, + sna_client_token=sna_client_token, + ) + instance = VerificationCheckInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the Verification Check resource was last updated - :rtype: datetime + :returns: The created VerificationCheckInstance """ - return self._properties['date_updated'] - - def __repr__(self): + payload, _, _ = await self._create_async( + code=code, + to=to, + verification_sid=verification_sid, + amount=amount, + payee=payee, + sna_client_token=sna_client_token, + ) + return VerificationCheckInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the VerificationCheckInstance and return response metadata + + :param code: The 4-10 character string being verified. + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param verification_sid: A SID that uniquely identifies the Verification Check. Either this parameter or the `to` phone number/[email](https://www.twilio.com/docs/verify/email) must be specified. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param sna_client_token: A sna client token received in sna url invocation response needs to be passed in Verification Check request and should match to get successful response. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + code=code, + to=to, + verification_sid=verification_sid, + amount=amount, + payee=payee, + sna_client_token=sna_client_token, + ) + instance = VerificationCheckInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 new file mode 100644 index 0000000000..2e59c8c4bb --- /dev/null +++ b/twilio/rest/verify/v2/service/webhook.py @@ -0,0 +1,1310 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class WebhookInstance(InstanceResource): + + class Methods(object): + GET = "GET" + POST = "POST" + + class Status(object): + ENABLED = "enabled" + DISABLED = "disabled" + + class Version(object): + V1 = "v1" + V2 = "v2" + + """ + :ivar sid: The unique string that we created to identify the Webhook resource. + :ivar service_sid: The unique SID identifier of the Service. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :ivar event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :ivar status: + :ivar version: + :ivar webhook_url: The URL associated with this Webhook. + :ivar webhook_method: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Webhook resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.event_types: Optional[List[str]] = payload.get("event_types") + self.status: Optional["WebhookInstance.Status"] = payload.get("status") + self.version: Optional["WebhookInstance.Version"] = payload.get("version") + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.webhook_method: Optional["WebhookInstance.Methods"] = payload.get( + "webhook_method" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: The updated WebhookInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_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, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> "WebhookInstance": + """ + Asynchronous coroutine to update the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: The updated WebhookInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + + def update_with_http_info( + 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, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :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 resource_version: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + + async def update_with_http_info_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, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :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 resource_version: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebhookContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the WebhookContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param sid: The Twilio-provided string that uniquely identifies the Webhook resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Webhooks/{sid}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = self._fetch() + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventTypes": serialize.map(event_types, lambda e: e), + "WebhookUrl": webhook_url, + "Status": status, + "Version": resource_version, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: The updated WebhookInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance and return response metadata + + :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 resource_version: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventTypes": serialize.map(event_types, lambda e: e), + "WebhookUrl": webhook_url, + "Status": status, + "Version": resource_version, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: The updated WebhookInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance and return response metadata + + :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 resource_version: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 WebhookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: + """ + Build an instance of WebhookInstance + + :param payload: Payload response from the API + """ + + return WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class WebhookList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Webhooks".format(**self._solution) + + def _create( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventTypes": serialize.map(event_types, lambda e: e), + "WebhookUrl": webhook_url, + "Status": status, + "Version": resource_version, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: The created WebhookInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + return WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: + """ + Create the WebhookInstance and return response metadata + + :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 resource_version: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + instance = WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventTypes": serialize.map(event_types, lambda e: e), + "WebhookUrl": webhook_url, + "Status": status, + "Version": resource_version, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: The created WebhookInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + return WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WebhookInstance and return response metadata + + :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 resource_version: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + instance = WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams WebhookInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams WebhookInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=self._solution) + + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: The Twilio-provided string that uniquely identifies the Webhook resource to update. + """ + return WebhookContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: The Twilio-provided string that uniquely identifies the Webhook resource to update. + """ + return WebhookContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/verify/v2/template.py b/twilio/rest/verify/v2/template.py new file mode 100644 index 0000000000..4dfecf8f57 --- /dev/null +++ b/twilio/rest/verify/v2/template.py @@ -0,0 +1,493 @@ +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.api_response import ApiResponse + +from twilio.base.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 stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TemplateInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TemplateInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TemplateInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TemplateInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with TemplatePage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TemplatePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with TemplatePage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TemplatePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..4704ee828a --- /dev/null +++ b/twilio/rest/verify/v2/verification_attempt.py @@ -0,0 +1,1000 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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" + + 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VerificationAttemptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VerificationAttemptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> VerificationAttemptInstance: + """ + Fetch the VerificationAttemptInstance + + + :returns: The fetched VerificationAttemptInstance + """ + payload, _, _ = self._fetch() + return VerificationAttemptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VerificationAttemptInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = VerificationAttemptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> VerificationAttemptInstance: + """ + Asynchronous coroutine to fetch the VerificationAttemptInstance + + + :returns: The fetched VerificationAttemptInstance + """ + payload, _, _ = await self._fetch_async() + return VerificationAttemptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VerificationAttemptInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = VerificationAttemptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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. + :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. + :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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams VerificationAttemptInstance and returns headers from first page + + + :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. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams VerificationAttemptInstance and returns headers from first page + + + :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. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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. + :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. + :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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists VerificationAttemptInstance and returns headers from first page + + + :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. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists VerificationAttemptInstance and returns headers from first page + + + :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. + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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. + :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. + :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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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. + :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: ApiResponse with VerificationAttemptPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = VerificationAttemptPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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. + :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: ApiResponse with VerificationAttemptPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = VerificationAttemptPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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..0f226478b5 --- /dev/null +++ b/twilio/rest/verify/v2/verification_attempts_summary.py @@ -0,0 +1,486 @@ +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.api_response import ApiResponse +from twilio.base.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" + RBM = "rbm" + + """ + :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. + :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. + :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 fetch_with_http_info( + 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, + ) -> ApiResponse: + """ + Fetch the VerificationAttemptsSummaryInstance with HTTP info + + :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. + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + 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_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VerificationAttemptsSummaryInstance with HTTP info + + :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. + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = 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" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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. + :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 + """ + payload, _, _ = self._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, + ) + return VerificationAttemptsSummaryInstance( + self._version, + payload, + ) + + def fetch_with_http_info( + 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, + ) -> ApiResponse: + """ + Fetch the VerificationAttemptsSummaryInstance and return response metadata + + :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. + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = VerificationAttemptsSummaryInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + 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. + :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 + """ + payload, _, _ = await self._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, + ) + return VerificationAttemptsSummaryInstance( + self._version, + payload, + ) + + async def fetch_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VerificationAttemptsSummaryInstance and return response metadata + + :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. + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = VerificationAttemptsSummaryInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..47bb8a9641 --- /dev/null +++ b/twilio/rest/video/v1/composition.py @@ -0,0 +1,1210 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CompositionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CompositionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CompositionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CompositionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the CompositionInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CompositionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CompositionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CompositionInstance: + """ + Fetch the CompositionInstance + + + :returns: The fetched CompositionInstance + """ + payload, _, _ = self._fetch() + return CompositionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CompositionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CompositionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CompositionInstance: + """ + Asynchronous coroutine to fetch the CompositionInstance + + + :returns: The fetched CompositionInstance + """ + payload, _, _ = await self._fetch_async() + return CompositionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CompositionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CompositionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + room_sid=room_sid, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + return CompositionInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the CompositionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + room_sid=room_sid, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + instance = CompositionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + room_sid=room_sid, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + return CompositionInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the CompositionInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + room_sid=room_sid, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + instance = CompositionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams CompositionInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + date_created_after=date_created_after, + date_created_before=date_created_before, + room_sid=room_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams CompositionInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + date_created_after=date_created_after, + date_created_before=date_created_before, + room_sid=room_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists CompositionInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + date_created_after=date_created_after, + date_created_before=date_created_before, + room_sid=room_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists CompositionInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with CompositionPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CompositionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with CompositionPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CompositionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 eb32a1110d..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'], limits['page_limit']) - - def list(self, status=values.unset, date_created_after=values.unset, - date_created_before=values.unset, room_sid=values.unset, limit=None, - page_size=None): - """ - Lists CompositionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param CompositionInstance.Status status: 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 be98526e74..16e7cb6f4a 100644 --- a/twilio/rest/video/v1/composition_hook.py +++ b/twilio/rest/video/v1/composition_hook.py @@ -1,590 +1,1645 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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. """ +class CompositionHookInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the CompositionHookList + class Format(object): + MP4 = "mp4" + WEBM = "webm" - :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 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") - :returns: twilio.rest.video.v1.composition_hook.CompositionHookList - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookList - """ - super(CompositionHookList, self).__init__(version) + self._solution = { + "sid": sid or self.sid, + } - # Path Solution - self._solution = {} - self._uri = '/CompositionHooks'.format(**self._solution) + 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. + 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 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) + :returns: CompositionHookContext for this CompositionHookInstance + """ + if self._context is None: + self._context = CompositionHookContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.composition_hook.CompositionHookInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the CompositionHookInstance - 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'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - 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): + async def delete_async(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. + 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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 await self._proxy.delete_async() - 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): + def delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of CompositionHookInstance records from the API. - Request is executed immediately + Deletes the CompositionHookInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - 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 self._proxy.delete_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CompositionHookInstance with HTTP info - return CompositionHookPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with success boolean, status code, and headers """ - Retrieve a specific page of CompositionHookInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + return await self._proxy.delete_with_http_info_async() - :returns: Page of CompositionHookInstance - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookPage + def fetch(self) -> "CompositionHookInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Fetch the CompositionHookInstance - return CompositionHookPage(self._version, response, self._solution) - 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): + :returns: The fetched CompositionHookInstance """ - Create the CompositionHookInstance + return self._proxy.fetch() + + async def fetch_async(self) -> "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, - }) + return await self._proxy.fetch_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CompositionHookInstance with HTTP info - return CompositionHookInstance(self._version, payload, ) - def get(self, sid): + :returns: ApiResponse with instance, status code, and headers """ - Constructs a CompositionHookContext + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CompositionHookInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return CompositionHookContext(self._version, sid=sid, ) + return await self._proxy.fetch_with_http_info_async() - def __call__(self, 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": """ - Constructs a CompositionHookContext + Update the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: The updated CompositionHookInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + trim=trim, + format=format, + resolution=resolution, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) - :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 update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CompositionHookInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + trim=trim, + format=format, + resolution=resolution, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CompositionHookInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: """ - Build an instance of CompositionHookInstance + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param dict payload: Payload response from the API + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.video.v1.composition_hook.CompositionHookInstance - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookInstance + def delete(self) -> bool: """ - return CompositionHookInstance(self._version, payload, ) + Deletes the CompositionHookInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the CompositionHookInstance and return response metadata -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. """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Initialize the CompositionHookContext - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch + headers = values.of({}) - :returns: twilio.rest.video.v1.composition_hook.CompositionHookContext - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookContext + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: """ - super(CompositionHookContext, self).__init__(version) + Asynchronous coroutine that deletes the CompositionHookInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/CompositionHooks/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise """ - Fetch the CompositionHookInstance + success, _, _ = await self._delete_async() + return success - :returns: The fetched CompositionHookInstance - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookInstance + async def delete_with_http_info_async(self) -> ApiResponse: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronous coroutine that deletes the CompositionHookInstance and return response metadata - return CompositionHookInstance(self._version, payload, sid=self._solution['sid'], ) - def delete(self): + :returns: ApiResponse with success boolean, status code, and headers """ - Deletes the CompositionHookInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def _fetch(self) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal helper for fetch operation - 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): + Returns: + tuple: (payload, status_code, headers) """ - 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 + headers = values.of({}) - :returns: The updated CompositionHookInstance - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookInstance + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> 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, - }) + Fetch the CompositionHookInstance - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - return CompositionHookInstance(self._version, payload, sid=self._solution['sid'], ) + :returns: The fetched CompositionHookInstance + """ + payload, _, _ = self._fetch() + return CompositionHookInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + def fetch_with_http_info(self) -> ApiResponse: """ - Provide a friendly representation + Fetch the CompositionHookInstance and return response metadata - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + payload, status_code, headers = self._fetch() + instance = CompositionHookInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation -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. """ + Returns: + tuple: (payload, status_code, headers) + """ - class Format(object): - MP4 = "mp4" - WEBM = "webm" + headers = values.of({}) - 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'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - @property - def _proxy(self): + async def fetch_async(self) -> CompositionHookInstance: """ - 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 fetch the CompositionHookInstance - :returns: CompositionHookContext for this CompositionHookInstance - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookContext - """ - if self._context is None: - self._context = CompositionHookContext(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 + :returns: The fetched CompositionHookInstance """ - return self._properties['account_sid'] + payload, _, _ = await self._fetch_async() + return CompositionHookInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - @property - def friendly_name(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Asynchronous coroutine to fetch the CompositionHookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['friendly_name'] + payload, status_code, headers = await self._fetch_async() + instance = CompositionHookInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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({}) - @property - def enabled(self): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - :returns: Whether the CompositionHook is active - :rtype: bool + Update the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: The updated CompositionHookInstance """ - return self._properties['enabled'] + payload, _, _ = self._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, + ) + return CompositionHookInstance( + self._version, payload, sid=self._solution["sid"] + ) - @property - def date_created(self): + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the CompositionHookInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = CompositionHookInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Enabled": serialize.boolean_to_string(enabled), + "VideoLayout": serialize.object(video_layout), + "AudioSources": serialize.map(audio_sources, lambda e: e), + "AudioSourcesExcluded": serialize.map( + audio_sources_excluded, lambda e: e + ), + "Trim": serialize.boolean_to_string(trim), + "Format": format, + "Resolution": resolution, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + payload, _, _ = await self._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, + ) + return CompositionHookInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CompositionHookInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = CompositionHookInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - return self._properties['date_created'] + Provide a friendly representation - @property - def date_updated(self): + :returns: Machine friendly representation """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CompositionHookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CompositionHookInstance: """ - return self._properties['date_updated'] + Build an instance of CompositionHookInstance - @property - def sid(self): + :param payload: Payload response from the API """ - :returns: The unique string that identifies the resource - :rtype: unicode + + return CompositionHookInstance(self._version, payload) + + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def audio_sources(self): + :returns: Machine friendly representation """ - :returns: The array of track names to include in the compositions created by the composition hook - :rtype: unicode + return "" + + +class CompositionHookList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['audio_sources'] + Initialize the CompositionHookList - @property - def audio_sources_excluded(self): + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/CompositionHooks" + + def _create( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 array of track names to exclude from the compositions created by the composition hook - :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['audio_sources_excluded'] + payload, _, _ = self._create( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + return CompositionHookInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the CompositionHookInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + instance = CompositionHookInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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"}) - @property - def video_layout(self): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: A JSON object that describes the video layout of the Composition - :rtype: dict + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + return CompositionHookInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the CompositionHookInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + instance = CompositionHookInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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['video_layout'] + 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 resolution(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 dimensions of the video image in pixels expressed as columns (width) and rows (height) - :rtype: unicode + 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['resolution'] + 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 trim(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: Whether intervals with no media are clipped - :rtype: bool + 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 stream_with_http_info( + 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, + ) -> tuple: """ - return self._properties['trim'] + Streams CompositionHookInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :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_response = self.page_with_http_info( + enabled=enabled, + date_created_after=date_created_after, + date_created_before=date_created_before, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - return self._properties['format'] + Asynchronously streams CompositionHookInstance and returns headers from first page - @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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The URL to send status information to your application - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + enabled=enabled, + date_created_after=date_created_after, + date_created_before=date_created_before, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists CompositionHookInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + enabled=enabled, + date_created_after=date_created_after, + date_created_before=date_created_before, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists CompositionHookInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with CompositionHookPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CompositionHookPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with CompositionHookPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CompositionHookPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 - def delete(self): + :param target_url: API-generated URL for the requested results page + + :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 d28e990095..ec04358b3d 100644 --- a/twilio/rest/video/v1/composition_settings.py +++ b/twilio/rest/video/v1/composition_settings.py @@ -1,324 +1,567 @@ -# 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.api_response import ApiResponse 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 CompositionSettingsList(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 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 - def __init__(self, version): + @property + def _proxy(self) -> "CompositionSettingsContext": """ - Initialize the CompositionSettingsList + 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: CompositionSettingsContext for this CompositionSettingsInstance + """ + if self._context is None: + self._context = CompositionSettingsContext( + self._version, + ) + return self._context - :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsList - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsList + 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": """ - super(CompositionSettingsList, self).__init__(version) + Create the CompositionSettingsInstance - # Path Solution - self._solution = {} + :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`. - def get(self): + :returns: The created CompositionSettingsInstance """ - Constructs a CompositionSettingsContext + return self._proxy.create( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + + async def create_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> "CompositionSettingsInstance": + """ + Asynchronous coroutine to create the CompositionSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. - :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsContext - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsContext + :returns: The created CompositionSettingsInstance """ - return CompositionSettingsContext(self._version, ) + 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 __call__(self): + def create_with_http_info( + 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, + ) -> ApiResponse: """ - Constructs a CompositionSettingsContext + Create the CompositionSettingsInstance with HTTP info - :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsContext - :rtype: twilio.rest.video.v1.composition_settings.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: ApiResponse with instance, status code, and headers """ - return CompositionSettingsContext(self._version, ) + return self._proxy.create_with_http_info( + 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): + async def create_with_http_info_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, + ) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to create the CompositionSettingsInstance with HTTP info - :returns: Machine friendly representation - :rtype: str + :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: ApiResponse with instance, status code, and headers """ - return '' + return await self._proxy.create_with_http_info_async( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + def fetch(self) -> "CompositionSettingsInstance": + """ + Fetch the CompositionSettingsInstance -class CompositionSettingsPage(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): + :returns: The fetched CompositionSettingsInstance """ - Initialize the CompositionSettingsPage + return self._proxy.fetch() + + async def fetch_async(self) -> "CompositionSettingsInstance": + """ + Asynchronous coroutine to 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 + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: """ - super(CompositionSettingsPage, self).__init__(version, response) + Fetch the CompositionSettingsInstance with HTTP info + - # Path Solution - self._solution = solution + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of CompositionSettingsInstance + Asynchronous coroutine to fetch the CompositionSettingsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return CompositionSettingsInstance(self._version, payload, ) + return await self._proxy.fetch_with_http_info_async() - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + + return "" class CompositionSettingsContext(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 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, + ) -> tuple: """ - Fetch the CompositionSettingsInstance + Internal helper for create operation - :returns: The fetched CompositionSettingsInstance - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance + Returns: + tuple: (payload, status_code, headers) """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return CompositionSettingsInstance(self._version, payload, ) + 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), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - 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): + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> CompositionSettingsInstance: """ Create the CompositionSettingsInstance - :param 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, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + payload, _, _ = self._create( + friendly_name=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 CompositionSettingsInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the CompositionSettingsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=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, + ) + instance = CompositionSettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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), + } + ) + headers = values.of({}) - return CompositionSettingsInstance(self._version, payload, ) + 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) + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + 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`. -class CompositionSettingsInstance(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: The created CompositionSettingsInstance + """ + payload, _, _ = await self._create_async( + friendly_name=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 CompositionSettingsInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the CompositionSettingsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=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, + ) + instance = CompositionSettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __init__(self, version, payload): + def _fetch(self) -> tuple: """ - Initialize the CompositionSettingsInstance + Internal helper for fetch operation - :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance + Returns: + tuple: (payload, status_code, headers) """ - 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 + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - :returns: CompositionSettingsContext for this CompositionSettingsInstance - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsContext + def fetch(self) -> CompositionSettingsInstance: """ - if self._context is None: - self._context = CompositionSettingsContext(self._version, ) - return self._context + Fetch the CompositionSettingsInstance - @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 + :returns: The fetched CompositionSettingsInstance """ - return self._properties['friendly_name'] + payload, _, _ = self._fetch() + return CompositionSettingsInstance( + self._version, + payload, + ) - @property - def aws_credentials_sid(self): + def fetch_with_http_info(self) -> ApiResponse: """ - :returns: The SID of the stored Credential resource - :rtype: unicode - """ - return self._properties['aws_credentials_sid'] + Fetch the CompositionSettingsInstance and return response metadata - @property - def aws_s3_url(self): + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The URL of the AWS S3 bucket where the compositions are stored - :rtype: unicode + payload, status_code, headers = self._fetch() + instance = CompositionSettingsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: """ - return self._properties['aws_s3_url'] + Internal async helper for fetch operation - @property - def aws_storage_enabled(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: Whether all compositions are written to the aws_s3_url - :rtype: bool + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CompositionSettingsInstance: """ - return self._properties['aws_storage_enabled'] + Asynchronous coroutine to fetch the CompositionSettingsInstance - @property - def encryption_key_sid(self): + + :returns: The fetched CompositionSettingsInstance """ - :returns: The SID of the Public Key resource used for encryption - :rtype: unicode + payload, _, _ = await self._fetch_async() + return CompositionSettingsInstance( + self._version, + payload, + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: """ - return self._properties['encryption_key_sid'] + Asynchronous coroutine to fetch the CompositionSettingsInstance and return response metadata - @property - def encryption_enabled(self): + + :returns: ApiResponse with instance, status code, and headers """ - :returns: Whether all compositions are stored in an encrypted form - :rtype: bool + payload, status_code, headers = await self._fetch_async() + instance = CompositionSettingsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - return self._properties['encryption_enabled'] + Provide a friendly representation - @property - def url(self): + :returns: Machine friendly representation """ - :returns: The absolute URL of the resource - :rtype: unicode + + return "" + + +class CompositionSettingsList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['url'] + Initialize the CompositionSettingsList + + :param version: Version that contains the resource - def fetch(self): """ - Fetch the CompositionSettingsInstance + super().__init__(version) - :returns: The fetched CompositionSettingsInstance - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance + def get(self) -> CompositionSettingsContext: """ - return self._proxy.fetch() + Constructs a CompositionSettingsContext - 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): """ - Create the CompositionSettingsInstance + return CompositionSettingsContext(self._version) - :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 + def __call__(self) -> CompositionSettingsContext: + """ + 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..f99a8322dd --- /dev/null +++ b/twilio/rest/video/v1/recording.py @@ -0,0 +1,1032 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + payload, _, _ = self._fetch() + return RecordingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RecordingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + payload, _, _ = await self._fetch_async() + return RecordingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RecordingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams RecordingInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams RecordingInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists RecordingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists RecordingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with RecordingPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RecordingPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with RecordingPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RecordingPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 4c848720a5..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'], limits['page_limit']) - - def list(self, status=values.unset, source_sid=values.unset, - grouping_sid=values.unset, date_created_after=values.unset, - date_created_before=values.unset, 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 719cc1fe43..ce2373eb9f 100644 --- a/twilio/rest/video/v1/recording_settings.py +++ b/twilio/rest/video/v1/recording_settings.py @@ -1,324 +1,567 @@ -# 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.api_response import ApiResponse 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 RecordingSettingsList(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 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 - def __init__(self, version): + @property + def _proxy(self) -> "RecordingSettingsContext": """ - Initialize the RecordingSettingsList + 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: RecordingSettingsContext for this RecordingSettingsInstance + """ + if self._context is None: + self._context = RecordingSettingsContext( + self._version, + ) + return self._context - :returns: twilio.rest.video.v1.recording_settings.RecordingSettingsList - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsList + 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": """ - super(RecordingSettingsList, self).__init__(version) + Create the RecordingSettingsInstance - # Path Solution - self._solution = {} + :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`. - def get(self): + :returns: The created RecordingSettingsInstance """ - Constructs a RecordingSettingsContext + return self._proxy.create( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + + async def create_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> "RecordingSettingsInstance": + """ + Asynchronous coroutine to create the RecordingSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. - :returns: twilio.rest.video.v1.recording_settings.RecordingSettingsContext - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsContext + :returns: The created RecordingSettingsInstance """ - return RecordingSettingsContext(self._version, ) + 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 __call__(self): + def create_with_http_info( + 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, + ) -> ApiResponse: """ - Constructs a RecordingSettingsContext + Create the RecordingSettingsInstance with HTTP info - :returns: twilio.rest.video.v1.recording_settings.RecordingSettingsContext - :rtype: twilio.rest.video.v1.recording_settings.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: ApiResponse with instance, status code, and headers """ - return RecordingSettingsContext(self._version, ) + return self._proxy.create_with_http_info( + 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): + async def create_with_http_info_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, + ) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to create the RecordingSettingsInstance with HTTP info - :returns: Machine friendly representation - :rtype: str + :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: ApiResponse with instance, status code, and headers """ - return '' + return await self._proxy.create_with_http_info_async( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + def fetch(self) -> "RecordingSettingsInstance": + """ + Fetch the RecordingSettingsInstance -class RecordingSettingsPage(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): + :returns: The fetched RecordingSettingsInstance """ - Initialize the RecordingSettingsPage + return self._proxy.fetch() + + async def fetch_async(self) -> "RecordingSettingsInstance": + """ + Asynchronous coroutine to 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 + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: """ - super(RecordingSettingsPage, self).__init__(version, response) + Fetch the RecordingSettingsInstance with HTTP info + - # Path Solution - self._solution = solution + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() - def get_instance(self, payload): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Build an instance of RecordingSettingsInstance + Asynchronous coroutine to fetch the RecordingSettingsInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return RecordingSettingsInstance(self._version, payload, ) + return await self._proxy.fetch_with_http_info_async() - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + + return "" class RecordingSettingsContext(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 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, + ) -> tuple: """ - Fetch the RecordingSettingsInstance + Internal helper for create operation - :returns: The fetched RecordingSettingsInstance - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsInstance + Returns: + tuple: (payload, status_code, headers) """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return RecordingSettingsInstance(self._version, payload, ) + 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), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - 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): + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> RecordingSettingsInstance: """ Create the RecordingSettingsInstance - :param 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, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + payload, _, _ = self._create( + friendly_name=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 RecordingSettingsInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the RecordingSettingsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=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, + ) + instance = RecordingSettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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), + } + ) + headers = values.of({}) - return RecordingSettingsInstance(self._version, payload, ) + 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) + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + 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`. -class RecordingSettingsInstance(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: The created RecordingSettingsInstance + """ + payload, _, _ = await self._create_async( + friendly_name=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 RecordingSettingsInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the RecordingSettingsInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=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, + ) + instance = RecordingSettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __init__(self, version, payload): + def _fetch(self) -> tuple: """ - Initialize the RecordingSettingsInstance + Internal helper for fetch operation - :returns: twilio.rest.video.v1.recording_settings.RecordingSettingsInstance - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsInstance + Returns: + tuple: (payload, status_code, headers) """ - 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 + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - :returns: RecordingSettingsContext for this RecordingSettingsInstance - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsContext + def fetch(self) -> RecordingSettingsInstance: """ - if self._context is None: - self._context = RecordingSettingsContext(self._version, ) - return self._context + Fetch the RecordingSettingsInstance - @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 + :returns: The fetched RecordingSettingsInstance """ - return self._properties['friendly_name'] + payload, _, _ = self._fetch() + return RecordingSettingsInstance( + self._version, + payload, + ) - @property - def aws_credentials_sid(self): + def fetch_with_http_info(self) -> ApiResponse: """ - :returns: The SID of the stored Credential resource - :rtype: unicode - """ - return self._properties['aws_credentials_sid'] + Fetch the RecordingSettingsInstance and return response metadata - @property - def aws_s3_url(self): + + :returns: ApiResponse with instance, status code, and headers """ - :returns: The URL of the AWS S3 bucket where the recordings are stored - :rtype: unicode + payload, status_code, headers = self._fetch() + instance = RecordingSettingsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: """ - return self._properties['aws_s3_url'] + Internal async helper for fetch operation - @property - def aws_storage_enabled(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: Whether all recordings are written to the aws_s3_url - :rtype: bool + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RecordingSettingsInstance: """ - return self._properties['aws_storage_enabled'] + Asynchronous coroutine to fetch the RecordingSettingsInstance - @property - def encryption_key_sid(self): + + :returns: The fetched RecordingSettingsInstance """ - :returns: The SID of the Public Key resource used for encryption - :rtype: unicode + payload, _, _ = await self._fetch_async() + return RecordingSettingsInstance( + self._version, + payload, + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: """ - return self._properties['encryption_key_sid'] + Asynchronous coroutine to fetch the RecordingSettingsInstance and return response metadata - @property - def encryption_enabled(self): + + :returns: ApiResponse with instance, status code, and headers """ - :returns: Whether all recordings are stored in an encrypted form - :rtype: bool + payload, status_code, headers = await self._fetch_async() + instance = RecordingSettingsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: """ - return self._properties['encryption_enabled'] + Provide a friendly representation - @property - def url(self): + :returns: Machine friendly representation """ - :returns: The absolute URL of the resource - :rtype: unicode + + return "" + + +class RecordingSettingsList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['url'] + Initialize the RecordingSettingsList + + :param version: Version that contains the resource - def fetch(self): """ - Fetch the RecordingSettingsInstance + super().__init__(version) - :returns: The fetched RecordingSettingsInstance - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsInstance + def get(self) -> RecordingSettingsContext: """ - return self._proxy.fetch() + Constructs a RecordingSettingsContext - 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): """ - Create the RecordingSettingsInstance + return RecordingSettingsContext(self._version) - :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 + def __call__(self) -> RecordingSettingsContext: + """ + 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 b704446ae3..cdc626b3e3 100644 --- a/twilio/rest/video/v1/room/__init__.py +++ b/twilio/rest/video/v1/room/__init__.py @@ -1,603 +1,1491 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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 +from twilio.rest.video.v1.room.transcriptions import TranscriptionsList -class RoomList(ListResource): - """ """ +class RoomInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the RoomList + class RoomStatus(object): + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + FAILED = "failed" - :param Version version: Version that contains the resource + class RoomType(object): + GROUP = "group" + GO = "go" + PEER_TO_PEER = "peer-to-peer" + GROUP_SMALL = "group-small" - :returns: twilio.rest.video.v1.room.RoomList - :rtype: twilio.rest.video.v1.room.RoomList - """ - super(RoomList, self).__init__(version) + class VideoCodec(object): + VP8 = "VP8" + H264 = "H264" - # Path Solution - self._solution = {} - self._uri = '/Rooms'.format(**self._solution) + """ + :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") - 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 + self._solution = { + "sid": sid or self.sid, + } - :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._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'], limits['page_limit']) + :returns: The fetched RoomInstance + """ + return self._proxy.fetch() - def list(self, status=values.unset, unique_name=values.unset, - date_created_after=values.unset, date_created_before=values.unset, - limit=None, page_size=None): + async def fetch_async(self) -> "RoomInstance": """ - Lists RoomInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine to fetch the RoomInstance - :param RoomInstance.RoomStatus status: 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 fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of RoomInstance records from the API. - Request is executed immediately + Fetch the RoomInstance with HTTP info - :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 - :returns: Page of RoomInstance - :rtype: twilio.rest.video.v1.room.RoomPage + :returns: ApiResponse with instance, status code, and headers """ - 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, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return RoomPage(self._version, response, self._solution) - - def get_page(self, target_url): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Retrieve a specific page of RoomInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the RoomInstance with HTTP info - :param str target_url: API-generated URL for the requested results page - :returns: Page of RoomInstance - :rtype: twilio.rest.video.v1.room.RoomPage + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.fetch_with_http_info_async() - return RoomPage(self._version, response, self._solution) - - def get(self, sid): + def update(self, status: "RoomInstance.RoomStatus") -> "RoomInstance": """ - Constructs a RoomContext + Update the RoomInstance - :param sid: The SID that identifies the resource to fetch + :param status: - :returns: twilio.rest.video.v1.room.RoomContext - :rtype: twilio.rest.video.v1.room.RoomContext + :returns: The updated RoomInstance """ - return RoomContext(self._version, sid=sid, ) + return self._proxy.update( + status=status, + ) - def __call__(self, sid): + async def update_async(self, status: "RoomInstance.RoomStatus") -> "RoomInstance": """ - Constructs a RoomContext - - :param sid: The SID that identifies the resource to fetch + Asynchronous coroutine to update the RoomInstance - :returns: twilio.rest.video.v1.room.RoomContext - :rtype: twilio.rest.video.v1.room.RoomContext - """ - return RoomContext(self._version, sid=sid, ) + :param status: - def __repr__(self): + :returns: The updated RoomInstance """ - Provide a friendly representation + return await self._proxy.update_async( + status=status, + ) - :returns: Machine friendly representation - :rtype: str + def update_with_http_info(self, status: "RoomInstance.RoomStatus") -> ApiResponse: """ - return '' + Update the RoomInstance with HTTP info + :param status: -class RoomPage(Page): - """ """ + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) - def __init__(self, version, response, solution): + async def update_with_http_info_async( + self, status: "RoomInstance.RoomStatus" + ) -> ApiResponse: """ - Initialize the RoomPage + Asynchronous coroutine to update the RoomInstance with HTTP info - :param Version version: Version that contains the resource - :param Response response: Response from the API + :param status: - :returns: twilio.rest.video.v1.room.RoomPage - :rtype: twilio.rest.video.v1.room.RoomPage + :returns: ApiResponse with instance, status code, and headers """ - super(RoomPage, self).__init__(version, response) + return await self._proxy.update_with_http_info_async( + status=status, + ) - # Path Solution - self._solution = solution + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + return self._proxy.participants - def get_instance(self, payload): + @property + def recording_rules(self) -> RecordingRulesList: """ - Build an instance of RoomInstance + Access the recording_rules + """ + return self._proxy.recording_rules - :param dict payload: Payload response from the API + @property + def recordings(self) -> RoomRecordingList: + """ + Access the recordings + """ + return self._proxy.recordings - :returns: twilio.rest.video.v1.room.RoomInstance - :rtype: twilio.rest.video.v1.room.RoomInstance + @property + def transcriptions(self) -> TranscriptionsList: """ - return RoomInstance(self._version, payload, ) + 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 RoomContext(InstanceContext): - """ """ - def __init__(self, version, sid): + def __init__(self, version: Version, sid: str): """ Initialize the RoomContext - :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 + :param version: Version that contains the resource + :param sid: The SID of the Room resource to update. """ - super(RoomContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Rooms/{sid}'.format(**self._solution) + self._solution = { + "sid": sid, + } + self._uri = "/Rooms/{sid}".format(**self._solution) + + self._participants: Optional[ParticipantList] = None + self._recording_rules: Optional[RecordingRulesList] = None + self._recordings: Optional[RoomRecordingList] = None + self._transcriptions: Optional[TranscriptionsList] = None + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ - # Dependents - self._recordings = None - self._participants = None + headers = values.of({}) - def fetch(self): + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoomInstance: """ Fetch the RoomInstance + :returns: The fetched RoomInstance - :rtype: twilio.rest.video.v1.room.RoomInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return RoomInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - return RoomInstance(self._version, payload, sid=self._solution['sid'], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoomInstance and return response metadata - def update(self, status): + + :returns: ApiResponse with instance, status code, and headers """ - Update the RoomInstance + payload, status_code, headers = self._fetch() + instance = RoomInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param RoomInstance.RoomStatus status: The new status of the resource + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: The updated RoomInstance - :rtype: twilio.rest.video.v1.room.RoomInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of({'Status': status, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers = values.of({}) - return RoomInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - @property - def recordings(self): + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RoomInstance: """ - Access the recordings + Asynchronous coroutine to fetch the RoomInstance - :returns: twilio.rest.video.v1.room.recording.RoomRecordingList - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingList + + :returns: The fetched RoomInstance """ - if self._recordings is None: - self._recordings = RoomRecordingList(self._version, room_sid=self._solution['sid'], ) - return self._recordings + payload, _, _ = await self._fetch_async() + return RoomInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - @property - def participants(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Access the participants + Asynchronous coroutine to fetch the RoomInstance and return response metadata + - :returns: twilio.rest.video.v1.room.room_participant.ParticipantList - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantList + :returns: ApiResponse with instance, status code, and headers """ - if self._participants is None: - self._participants = ParticipantList(self._version, room_sid=self._solution['sid'], ) - return self._participants + payload, status_code, headers = await self._fetch_async() + instance = RoomInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + def _update(self, status: "RoomInstance.RoomStatus") -> tuple: """ - Provide a friendly representation + Internal helper for update operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - 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): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - class RoomStatus(object): - IN_PROGRESS = "in-progress" - COMPLETED = "completed" - FAILED = "failed" + headers["Accept"] = "application/json" - class RoomType(object): - PEER_TO_PEER = "peer-to-peer" - GROUP = "group" - GROUP_SMALL = "group-small" + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - class VideoCodec(object): - VP8 = "VP8" - H264 = "H264" + def update(self, status: "RoomInstance.RoomStatus") -> RoomInstance: + """ + Update the RoomInstance - 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'), - } + :param status: - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + :returns: The updated RoomInstance + """ + payload, _, _ = self._update(status=status) + return RoomInstance(self._version, payload, sid=self._solution["sid"]) - @property - def _proxy(self): + def update_with_http_info(self, status: "RoomInstance.RoomStatus") -> ApiResponse: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Update the RoomInstance and return response metadata - :returns: RoomContext for this RoomInstance - :rtype: twilio.rest.video.v1.room.RoomContext + :param status: + + :returns: ApiResponse with instance, status code, and headers """ - if self._context is None: - self._context = RoomContext(self._version, sid=self._solution['sid'], ) - return self._context + payload, status_code, headers = self._update(status=status) + instance = RoomInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def sid(self): + async def _update_async(self, status: "RoomInstance.RoomStatus") -> tuple: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['sid'] - @property - def status(self): + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async(self, status: "RoomInstance.RoomStatus") -> RoomInstance: """ - :returns: The status of the room - :rtype: RoomInstance.RoomStatus + Asynchronous coroutine to update the RoomInstance + + :param status: + + :returns: The updated RoomInstance """ - return self._properties['status'] + payload, _, _ = await self._update_async(status=status) + return RoomInstance(self._version, payload, sid=self._solution["sid"]) - @property - def date_created(self): + async def update_with_http_info_async( + self, status: "RoomInstance.RoomStatus" + ) -> ApiResponse: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Asynchronous coroutine to update the RoomInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['date_created'] + payload, status_code, headers = await self._update_async(status=status) + instance = RoomInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def date_updated(self): + def participants(self) -> ParticipantList: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Access the participants """ - return self._properties['date_updated'] + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["sid"], + ) + return self._participants @property - def account_sid(self): + def recording_rules(self) -> RecordingRulesList: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Access the recording_rules """ - return self._properties['account_sid'] + if self._recording_rules is None: + self._recording_rules = RecordingRulesList( + self._version, + self._solution["sid"], + ) + return self._recording_rules @property - def enable_turn(self): + def recordings(self) -> RoomRecordingList: """ - :returns: Enable Twilio's Network Traversal TURN service - :rtype: bool + Access the recordings """ - return self._properties['enable_turn'] + if self._recordings is None: + self._recordings = RoomRecordingList( + self._version, + self._solution["sid"], + ) + return self._recordings @property - def unique_name(self): + def transcriptions(self) -> TranscriptionsList: """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + Access the transcriptions """ - return self._properties['unique_name'] + if self._transcriptions is None: + self._transcriptions = TranscriptionsList( + self._version, + self._solution["sid"], + ) + return self._transcriptions - @property - def status_callback(self): + def __repr__(self) -> str: """ - :returns: The URL to send status information to your application - :rtype: unicode - """ - return self._properties['status_callback'] + Provide a friendly representation - @property - def status_callback_method(self): + :returns: Machine friendly representation """ - :returns: The HTTP method we use to call status_callback - :rtype: unicode + 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: """ - return self._properties['status_callback_method'] + Build an instance of RoomInstance - @property - def end_time(self): + :param payload: Payload response from the API """ - :returns: The UTC end time of the room in UTC ISO 8601 format - :rtype: datetime + + return RoomInstance(self._version, payload) + + def __repr__(self) -> str: """ - return self._properties['end_time'] + Provide a friendly representation - @property - def duration(self): + :returns: Machine friendly representation """ - :returns: The duration of the room in seconds - :rtype: unicode + return "" + + +class RoomList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['duration'] + Initialize the RoomList - @property - def type(self): + :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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - :returns: The type of room - :rtype: RoomInstance.RoomType + 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['type'] + payload, _, _ = self._create( + enable_turn=enable_turn, + type=type, + unique_name=unique_name, + status_callback=status_callback, + status_callback_method=status_callback_method, + max_participants=max_participants, + record_participants_on_connect=record_participants_on_connect, + transcribe_participants_on_connect=transcribe_participants_on_connect, + video_codecs=video_codecs, + media_region=media_region, + recording_rules=recording_rules, + transcriptions_configuration=transcriptions_configuration, + audio_only=audio_only, + max_participant_duration=max_participant_duration, + empty_room_timeout=empty_room_timeout, + unused_room_timeout=unused_room_timeout, + large_room=large_room, + ) + return RoomInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the RoomInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + enable_turn=enable_turn, + type=type, + unique_name=unique_name, + status_callback=status_callback, + status_callback_method=status_callback_method, + max_participants=max_participants, + record_participants_on_connect=record_participants_on_connect, + transcribe_participants_on_connect=transcribe_participants_on_connect, + video_codecs=video_codecs, + media_region=media_region, + recording_rules=recording_rules, + transcriptions_configuration=transcriptions_configuration, + audio_only=audio_only, + max_participant_duration=max_participant_duration, + empty_room_timeout=empty_room_timeout, + unused_room_timeout=unused_room_timeout, + large_room=large_room, + ) + instance = RoomInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "EnableTurn": serialize.boolean_to_string(enable_turn), + "Type": type, + "UniqueName": unique_name, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "MaxParticipants": max_participants, + "RecordParticipantsOnConnect": serialize.boolean_to_string( + record_participants_on_connect + ), + "TranscribeParticipantsOnConnect": serialize.boolean_to_string( + transcribe_participants_on_connect + ), + "VideoCodecs": serialize.map(video_codecs, lambda e: e), + "MediaRegion": media_region, + "RecordingRules": serialize.object(recording_rules), + "TranscriptionsConfiguration": serialize.object( + transcriptions_configuration + ), + "AudioOnly": serialize.boolean_to_string(audio_only), + "MaxParticipantDuration": max_participant_duration, + "EmptyRoomTimeout": empty_room_timeout, + "UnusedRoomTimeout": unused_room_timeout, + "LargeRoom": serialize.boolean_to_string(large_room), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def max_participants(self): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 """ - :returns: The maximum number of concurrent Participants allowed in the room - :rtype: unicode + payload, _, _ = await self._create_async( + enable_turn=enable_turn, + type=type, + unique_name=unique_name, + status_callback=status_callback, + status_callback_method=status_callback_method, + max_participants=max_participants, + record_participants_on_connect=record_participants_on_connect, + transcribe_participants_on_connect=transcribe_participants_on_connect, + video_codecs=video_codecs, + media_region=media_region, + recording_rules=recording_rules, + transcriptions_configuration=transcriptions_configuration, + audio_only=audio_only, + max_participant_duration=max_participant_duration, + empty_room_timeout=empty_room_timeout, + unused_room_timeout=unused_room_timeout, + large_room=large_room, + ) + return RoomInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the RoomInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + enable_turn=enable_turn, + type=type, + unique_name=unique_name, + status_callback=status_callback, + status_callback_method=status_callback_method, + max_participants=max_participants, + record_participants_on_connect=record_participants_on_connect, + transcribe_participants_on_connect=transcribe_participants_on_connect, + video_codecs=video_codecs, + media_region=media_region, + recording_rules=recording_rules, + transcriptions_configuration=transcriptions_configuration, + audio_only=audio_only, + max_participant_duration=max_participant_duration, + empty_room_timeout=empty_room_timeout, + unused_room_timeout=unused_room_timeout, + large_room=large_room, + ) + instance = RoomInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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]: """ - return self._properties['max_participants'] + 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. - @property - def record_participants_on_connect(self): + :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 """ - :returns: Whether to start recording when Participants connect - :rtype: bool + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoomInstance]: """ - return self._properties['record_participants_on_connect'] + 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. - @property - def video_codecs(self): + :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 """ - :returns: An array of the video codecs that are supported when publishing a track in the room - :rtype: RoomInstance.VideoCodec + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: """ - return self._properties['video_codecs'] + Streams RoomInstance and returns headers from first page - @property - def media_region(self): + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The region for the media server in Group Rooms - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - return self._properties['media_region'] + Asynchronously streams RoomInstance and returns headers from first page - @property - def url(self): + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: The absolute URL of the resource - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - return self._properties['url'] + Lists RoomInstance 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 "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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists RoomInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists RoomInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - :returns: The URLs of related resources - :rtype: unicode + Retrieve a single page of RoomInstance records from the API. + Request is executed immediately + + :param status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param unique_name: Read only rooms with the this `unique_name`. + :param date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoomInstance """ - return self._properties['links'] + data = values.of( + { + "Status": status, + "UniqueName": unique_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = 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 - def fetch(self): + :returns: Page of RoomInstance """ - Fetch the 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, + } + ) - :returns: The fetched RoomInstance - :rtype: twilio.rest.video.v1.room.RoomInstance + headers = values.of({"Content-Type": "application/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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with RoomPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RoomPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with RoomPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RoomPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> RoomPage: """ - return self._proxy.fetch() + Retrieve a specific page of RoomInstance records from the API. + Request is executed immediately - def update(self, status): + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoomInstance """ - Update the 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 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..fdee154a0c --- /dev/null +++ b/twilio/rest/video/v1/room/participant/__init__.py @@ -0,0 +1,1120 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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, + ) + + def update_with_http_info( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ApiResponse: + """ + Update the ParticipantInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = self._fetch() + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = await self._fetch_async() + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ParticipantInstance: + """ + Update the ParticipantInstance + + :param status: + + :returns: The updated ParticipantInstance + """ + payload, _, _ = self._update(status=status) + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ApiResponse: + """ + Update the ParticipantInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._update_async(status=status) + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams ParticipantInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams ParticipantInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists ParticipantInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ParticipantPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ParticipantPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..4a024d06a2 --- /dev/null +++ b/twilio/rest/video/v1/room/participant/anonymize.py @@ -0,0 +1,313 @@ +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.api_response import ApiResponse +from twilio.base.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 update_with_http_info(self) -> ApiResponse: + """ + Update the AnonymizeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info() + + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the AnonymizeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self) -> AnonymizeInstance: + """ + Update the AnonymizeInstance + + + :returns: The updated AnonymizeInstance + """ + payload, _, _ = self._update() + return AnonymizeInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info(self) -> ApiResponse: + """ + Update the AnonymizeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update() + instance = AnonymizeInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async(self) -> AnonymizeInstance: + """ + Asynchronous coroutine to update the AnonymizeInstance + + + :returns: The updated AnonymizeInstance + """ + payload, _, _ = await self._update_async() + return AnonymizeInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the AnonymizeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async() + instance = AnonymizeInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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..ec1ebf09a4 --- /dev/null +++ b/twilio/rest/video/v1/room/participant/published_track.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, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PublishedTrackInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PublishedTrackInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PublishedTrackInstance: + """ + Fetch the PublishedTrackInstance + + + :returns: The fetched PublishedTrackInstance + """ + payload, _, _ = self._fetch() + return PublishedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PublishedTrackInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PublishedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> PublishedTrackInstance: + """ + Asynchronous coroutine to fetch the PublishedTrackInstance + + + :returns: The fetched PublishedTrackInstance + """ + payload, _, _ = await self._fetch_async() + return PublishedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PublishedTrackInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PublishedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PublishedTrackInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PublishedTrackInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PublishedTrackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PublishedTrackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PublishedTrackPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PublishedTrackPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PublishedTrackPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PublishedTrackPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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..f13f7e6473 --- /dev/null +++ b/twilio/rest/video/v1/room/participant/subscribe_rules.py @@ -0,0 +1,310 @@ +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.api_response import ApiResponse + +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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SubscribeRulesInstance: + """ + Fetch the SubscribeRulesInstance + + + :returns: The fetched SubscribeRulesInstance + """ + payload, _, _ = self._fetch() + return SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscribeRulesInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SubscribeRulesInstance: + """ + Asynchronously fetch the SubscribeRulesInstance + + + :returns: The fetched SubscribeRulesInstance + """ + payload, _, _ = await self._fetch_async() + return SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously fetch the SubscribeRulesInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, rules: Union[object, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 updated SubscribeRulesInstance + """ + payload, _, _ = self._update(rules=rules) + return SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def update_with_http_info( + self, rules: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Update the SubscribeRulesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(rules=rules) + instance = SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, rules: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 updated SubscribeRulesInstance + """ + payload, _, _ = await self._update_async(rules=rules) + return SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + async def update_with_http_info_async( + self, rules: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously update the SubscribeRulesInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(rules=rules) + instance = SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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..de2ef19592 --- /dev/null +++ b/twilio/rest/video/v1/room/participant/subscribed_track.py @@ -0,0 +1,719 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscribedTrackInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SubscribedTrackInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SubscribedTrackInstance: + """ + Fetch the SubscribedTrackInstance + + + :returns: The fetched SubscribedTrackInstance + """ + payload, _, _ = self._fetch() + return SubscribedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscribedTrackInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SubscribedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SubscribedTrackInstance: + """ + Asynchronous coroutine to fetch the SubscribedTrackInstance + + + :returns: The fetched SubscribedTrackInstance + """ + payload, _, _ = await self._fetch_async() + return SubscribedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SubscribedTrackInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SubscribedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SubscribedTrackInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SubscribedTrackInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SubscribedTrackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SubscribedTrackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=self._solution) + + async def 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, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SubscribedTrackPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SubscribedTrackPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SubscribedTrackPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SubscribedTrackPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 705afa38ca..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'], limits['page_limit']) - - def list(self, status=values.unset, source_sid=values.unset, - date_created_after=values.unset, date_created_before=values.unset, - limit=None, page_size=None): - """ - Lists RoomRecordingInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param RoomRecordingInstance.Status status: 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..d399cd03d4 --- /dev/null +++ b/twilio/rest/video/v1/room/recording_rules.py @@ -0,0 +1,271 @@ +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.api_response import ApiResponse + +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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingRulesInstance: + """ + Fetch the RecordingRulesInstance + + + :returns: The fetched RecordingRulesInstance + """ + payload, _, _ = self._fetch() + return RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingRulesInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RecordingRulesInstance: + """ + Asynchronously fetch the RecordingRulesInstance + + + :returns: The fetched RecordingRulesInstance + """ + payload, _, _ = await self._fetch_async() + return RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously fetch the RecordingRulesInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, rules: Union[object, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, rules: Union[object, object] = values.unset + ) -> RecordingRulesInstance: + """ + Update the RecordingRulesInstance + + :param rules: A JSON-encoded array of recording rules. + + :returns: The updated RecordingRulesInstance + """ + payload, _, _ = self._update(rules=rules) + return RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def update_with_http_info( + self, rules: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Update the RecordingRulesInstance and return response metadata + + :param rules: A JSON-encoded array of recording rules. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(rules=rules) + instance = RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, rules: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 updated RecordingRulesInstance + """ + payload, _, _ = await self._update_async(rules=rules) + return RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + async def update_with_http_info_async( + self, rules: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously update the RecordingRulesInstance and return response metadata + + :param rules: A JSON-encoded array of recording rules. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(rules=rules) + instance = RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 99e06669c5..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'], limits['page_limit']) - - def list(self, status=values.unset, identity=values.unset, - date_created_after=values.unset, date_created_before=values.unset, - limit=None, page_size=None): - """ - Lists ParticipantInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param ParticipantInstance.Status status: 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 897aa7c338..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'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists PublishedTrackInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of PublishedTrackInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of PublishedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackPage - """ - 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 e560aeda59..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'], limits['page_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..697904b713 --- /dev/null +++ b/twilio/rest/video/v1/room/room_recording.py @@ -0,0 +1,979 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoomRecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoomRecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoomRecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoomRecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the RoomRecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoomRecordingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoomRecordingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoomRecordingInstance: + """ + Fetch the RoomRecordingInstance + + + :returns: The fetched RoomRecordingInstance + """ + payload, _, _ = self._fetch() + return RoomRecordingInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoomRecordingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoomRecordingInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RoomRecordingInstance: + """ + Asynchronous coroutine to fetch the RoomRecordingInstance + + + :returns: The fetched RoomRecordingInstance + """ + payload, _, _ = await self._fetch_async() + return RoomRecordingInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoomRecordingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoomRecordingInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 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 stream_with_http_info( + 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, + ) -> tuple: + """ + Streams RoomRecordingInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + source_sid=source_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams RoomRecordingInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + source_sid=source_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists RoomRecordingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + source_sid=source_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists RoomRecordingInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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, solution=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, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with RoomRecordingPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RoomRecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with RoomRecordingPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RoomRecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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/video/v1/room/transcriptions.py b/twilio/rest/video/v1/room/transcriptions.py new file mode 100644 index 0000000000..78ee6ceefe --- /dev/null +++ b/twilio/rest/video/v1/room/transcriptions.py @@ -0,0 +1,1033 @@ +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.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TranscriptionsInstance(InstanceResource): + + class Status(object): + STARTED = "started" + STOPPED = "stopped" + FAILED = "failed" + + """ + :ivar ttid: The unique string that we created to identify the transcriptions resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Room resource. + :ivar room_sid: The SID of the transcriptions's room. + :ivar source_sid: The SID of the transcriptions's associated call. + :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 start_time: The time of transcriptions connected to the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :ivar end_time: The time when the transcriptions disconnected from the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :ivar duration: The duration in seconds that the transcriptions were `connected`. Populated only after the transcriptions is `stopped`. + :ivar url: The absolute URL of the resource. + :ivar configuration: An JSON 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. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + room_sid: str, + ttid: Optional[str] = None, + ): + super().__init__(version) + + self.ttid: Optional[str] = payload.get("ttid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.source_sid: Optional[str] = payload.get("source_sid") + self.status: Optional["TranscriptionsInstance.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.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.configuration: Optional[Dict[str, object]] = payload.get("configuration") + + self._solution = { + "room_sid": room_sid, + "ttid": ttid or self.ttid, + } + + self._context: Optional[TranscriptionsContext] = None + + @property + def _proxy(self) -> "TranscriptionsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TranscriptionsContext for this TranscriptionsInstance + """ + if self._context is None: + self._context = TranscriptionsContext( + self._version, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + return self._context + + def fetch(self) -> "TranscriptionsInstance": + """ + Fetch the TranscriptionsInstance + + + :returns: The fetched TranscriptionsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TranscriptionsInstance": + """ + Asynchronous coroutine to fetch the TranscriptionsInstance + + + :returns: The fetched TranscriptionsInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> "TranscriptionsInstance": + """ + Update the TranscriptionsInstance + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: The updated TranscriptionsInstance + """ + return self._proxy.update( + status=status, + configuration=configuration, + ) + + async def update_async( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> "TranscriptionsInstance": + """ + Asynchronous coroutine to update the TranscriptionsInstance + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: The updated TranscriptionsInstance + """ + return await self._proxy.update_async( + status=status, + configuration=configuration, + ) + + def update_with_http_info( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the TranscriptionsInstance with HTTP info + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + configuration=configuration, + ) + + async def update_with_http_info_async( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TranscriptionsInstance with HTTP info + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + configuration=configuration, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TranscriptionsContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str, ttid: str): + """ + Initialize the TranscriptionsContext + + :param version: Version that contains the resource + :param room_sid: The SID of the room with the transcriptions resource to update. + :param ttid: The Twilio type id of the transcriptions resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "ttid": ttid, + } + self._uri = "/Rooms/{room_sid}/Transcriptions/{ttid}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptionsInstance: + """ + Fetch the TranscriptionsInstance + + + :returns: The fetched TranscriptionsInstance + """ + payload, _, _ = self._fetch() + return TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TranscriptionsInstance: + """ + Asynchronous coroutine to fetch the TranscriptionsInstance + + + :returns: The fetched TranscriptionsInstance + """ + payload, _, _ = await self._fetch_async() + return TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + "Configuration": serialize.object(configuration), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> TranscriptionsInstance: + """ + Update the TranscriptionsInstance + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: The updated TranscriptionsInstance + """ + payload, _, _ = self._update(status=status, configuration=configuration) + return TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + + def update_with_http_info( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the TranscriptionsInstance and return response metadata + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, configuration=configuration + ) + instance = TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + "Configuration": serialize.object(configuration), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> TranscriptionsInstance: + """ + Asynchronous coroutine to update the TranscriptionsInstance + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: The updated TranscriptionsInstance + """ + payload, _, _ = await self._update_async( + status=status, configuration=configuration + ) + return TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + + async def update_with_http_info_async( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TranscriptionsInstance and return response metadata + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, configuration=configuration + ) + instance = TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 TranscriptionsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TranscriptionsInstance: + """ + Build an instance of TranscriptionsInstance + + :param payload: Payload response from the API + """ + + return TranscriptionsInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TranscriptionsList(ListResource): + + def __init__(self, version: Version, room_sid: str): + """ + Initialize the TranscriptionsList + + :param version: Version that contains the resource + :param room_sid: The SID of the room with the transcriptions resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + } + self._uri = "/Rooms/{room_sid}/Transcriptions".format(**self._solution) + + def _create(self, configuration: Union[object, object] = values.unset) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Configuration": serialize.object(configuration), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, configuration: Union[object, object] = values.unset + ) -> TranscriptionsInstance: + """ + Create the TranscriptionsInstance + + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: The created TranscriptionsInstance + """ + payload, _, _ = self._create(configuration=configuration) + return TranscriptionsInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def create_with_http_info( + self, configuration: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the TranscriptionsInstance and return response metadata + + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(configuration=configuration) + instance = TranscriptionsInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, configuration: Union[object, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Configuration": serialize.object(configuration), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, configuration: Union[object, object] = values.unset + ) -> TranscriptionsInstance: + """ + Asynchronously create the TranscriptionsInstance + + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: The created TranscriptionsInstance + """ + payload, _, _ = await self._create_async(configuration=configuration) + return TranscriptionsInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + async def create_with_http_info_async( + self, configuration: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the TranscriptionsInstance and return response metadata + + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + configuration=configuration + ) + instance = TranscriptionsInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TranscriptionsInstance]: + """ + Streams TranscriptionsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TranscriptionsInstance]: + """ + Asynchronously streams TranscriptionsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TranscriptionsInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TranscriptionsInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionsInstance]: + """ + Lists TranscriptionsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionsInstance]: + """ + Asynchronously lists TranscriptionsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TranscriptionsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TranscriptionsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptionsPage: + """ + Retrieve a single page of TranscriptionsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptionsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptionsPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptionsPage: + """ + Asynchronously retrieve a single page of TranscriptionsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptionsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptionsPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptionsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TranscriptionsPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptionsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TranscriptionsPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> TranscriptionsPage: + """ + Retrieve a specific page of TranscriptionsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptionsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TranscriptionsPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> TranscriptionsPage: + """ + Asynchronously retrieve a specific page of TranscriptionsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptionsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TranscriptionsPage(self._version, response, solution=self._solution) + + def get(self, ttid: str) -> TranscriptionsContext: + """ + Constructs a TranscriptionsContext + + :param ttid: The Twilio type id of the transcriptions resource to update. + """ + return TranscriptionsContext( + self._version, room_sid=self._solution["room_sid"], ttid=ttid + ) + + def __call__(self, ttid: str) -> TranscriptionsContext: + """ + Constructs a TranscriptionsContext + + :param ttid: The Twilio type id of the transcriptions resource to update. + """ + return TranscriptionsContext( + self._version, room_sid=self._solution["room_sid"], ttid=ttid + ) + + 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..3bcc12e228 --- /dev/null +++ b/twilio/rest/voice/VoiceBase.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.voice.v1 import V1 +from twilio.rest.voice.v3 import V3 + + +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 + self._v3: Optional[V3] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Voice + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Voice + """ + 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/voice/__init__.py b/twilio/rest/voice/__init__.py index 7107d27d3b..019a3a2058 100644 --- a/twilio/rest/voice/__init__.py +++ b/twilio/rest/voice/__init__.py @@ -1,53 +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' +class Voice(VoiceBase): + @property + def archived_calls(self) -> ArchivedCallList: + warn( + "archived_calls is deprecated. Use v1.archived_calls instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.archived_calls - # Versions - self._v1 = None + @property + def byoc_trunks(self) -> ByocTrunkList: + warn( + "byoc_trunks is deprecated. Use v1.byoc_trunks instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.byoc_trunks @property - def 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 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 - def __repr__(self): - """ - Provide a friendly representation + @property + def ip_records(self) -> IpRecordList: + warn( + "ip_records is deprecated. Use v1.ip_records instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.ip_records - :returns: Machine friendly representation - :rtype: str - """ - return '' + @property + def source_ip_mappings(self) -> SourceIpMappingList: + warn( + "source_ip_mappings is deprecated. Use v1.source_ip_mappings instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.source_ip_mappings diff --git a/twilio/rest/voice/v1/__init__.py b/twilio/rest/voice/v1/__init__.py index 6727079c28..75c0c7fc74 100644 --- a/twilio/rest/voice/v1/__init__.py +++ b/twilio/rest/voice/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 - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. """ +from typing import Optional from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.voice.v1.archived_call import ArchivedCallList +from twilio.rest.voice.v1.byoc_trunk import ByocTrunkList +from twilio.rest.voice.v1.connection_policy import ConnectionPolicyList from twilio.rest.voice.v1.dialing_permissions import DialingPermissionsList +from twilio.rest.voice.v1.ip_record import IpRecordList +from twilio.rest.voice.v1.source_ip_mapping import SourceIpMappingList class V1(Version): - def __init__(self, domain): + 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._dialing_permissions = 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 dialing_permissions(self): - """ - :rtype: twilio.rest.voice.v1.dialing_permissions.DialingPermissionsList - """ + def archived_calls(self) -> ArchivedCallList: + if self._archived_calls is None: + self._archived_calls = ArchivedCallList(self) + return self._archived_calls + + @property + def byoc_trunks(self) -> ByocTrunkList: + if self._byoc_trunks is None: + self._byoc_trunks = ByocTrunkList(self) + return self._byoc_trunks + + @property + def connection_policies(self) -> ConnectionPolicyList: + if self._connection_policies is None: + self._connection_policies = ConnectionPolicyList(self) + return self._connection_policies + + @property + def dialing_permissions(self) -> DialingPermissionsList: if self._dialing_permissions is None: self._dialing_permissions = DialingPermissionsList(self) return self._dialing_permissions - def __repr__(self): + @property + def ip_records(self) -> IpRecordList: + if self._ip_records is None: + self._ip_records = IpRecordList(self) + return self._ip_records + + @property + def source_ip_mappings(self) -> SourceIpMappingList: + if self._source_ip_mappings is None: + self._source_ip_mappings = SourceIpMappingList(self) + return self._source_ip_mappings + + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :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..090f21d452 --- /dev/null +++ b/twilio/rest/voice/v1/archived_call.py @@ -0,0 +1,156 @@ +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.api_response import ApiResponse +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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ArchivedCallInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ArchivedCallInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + 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 + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ArchivedCallInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ArchivedCallList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ArchivedCallList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, date: date, sid: str) -> ArchivedCallContext: + """ + Constructs a ArchivedCallContext + + :param date: The date of the Call in UTC. + :param sid: The Twilio-provided Call SID that uniquely identifies the Call resource to delete + """ + return ArchivedCallContext(self._version, date=date, sid=sid) + + def __call__(self, date: date, sid: str) -> ArchivedCallContext: + """ + Constructs a ArchivedCallContext + + :param date: The date of the Call in UTC. + :param sid: The Twilio-provided Call SID that uniquely identifies the Call resource to delete + """ + return ArchivedCallContext(self._version, date=date, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/voice/v1/byoc_trunk.py b/twilio/rest/voice/v1/byoc_trunk.py new file mode 100644 index 0000000000..f6e053c0dc --- /dev/null +++ b/twilio/rest/voice/v1/byoc_trunk.py @@ -0,0 +1,1472 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ByocTrunkInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the BYOC Trunk resource. + :ivar sid: The unique string that that we created to identify the BYOC Trunk resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar voice_url: The URL we call using the `voice_method` when the BYOC Trunk receives a call. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML requested from `voice_url`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar status_callback_url: The URL that we call to pass status parameters (such as call ended) to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback_url`. Either `GET` or `POST`. + :ivar cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :ivar connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :ivar from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \"call back\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \"sip.twilio.com\". + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.voice_url: Optional[str] = payload.get("voice_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.status_callback_url: Optional[str] = payload.get("status_callback_url") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.cnam_lookup_enabled: Optional[bool] = payload.get("cnam_lookup_enabled") + self.connection_policy_sid: Optional[str] = payload.get("connection_policy_sid") + self.from_domain_sid: Optional[str] = payload.get("from_domain_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[ByocTrunkContext] = None + + @property + def _proxy(self) -> "ByocTrunkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ByocTrunkContext for this ByocTrunkInstance + """ + if self._context is None: + self._context = ByocTrunkContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ByocTrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ByocTrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ByocTrunkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ByocTrunkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "ByocTrunkInstance": + """ + Fetch the ByocTrunkInstance + + + :returns: The fetched ByocTrunkInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ByocTrunkInstance": + """ + Asynchronous coroutine to fetch the ByocTrunkInstance + + + :returns: The fetched ByocTrunkInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ByocTrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ByocTrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> "ByocTrunkInstance": + """ + Update the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The updated ByocTrunkInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> "ByocTrunkInstance": + """ + Asynchronous coroutine to update the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The updated ByocTrunkInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ByocTrunkInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ByocTrunkInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ByocTrunkContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ByocTrunkContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the BYOC Trunk resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/ByocTrunks/{sid}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ByocTrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ByocTrunkInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ByocTrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ByocTrunkInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ByocTrunkInstance: + """ + Fetch the ByocTrunkInstance + + + :returns: The fetched ByocTrunkInstance + """ + payload, _, _ = self._fetch() + return ByocTrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ByocTrunkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ByocTrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ByocTrunkInstance: + """ + Asynchronous coroutine to fetch the ByocTrunkInstance + + + :returns: The fetched ByocTrunkInstance + """ + payload, _, _ = await self._fetch_async() + return ByocTrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ByocTrunkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ByocTrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ByocTrunkInstance: + """ + Update the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The updated ByocTrunkInstance + """ + payload, _, _ = self._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 ByocTrunkInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ByocTrunkInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = ByocTrunkInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._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 ByocTrunkInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ByocTrunkInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = ByocTrunkInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, 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 ByocTrunkPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ByocTrunkInstance: + """ + Build an instance of ByocTrunkInstance + + :param payload: Payload response from the API + """ + + return ByocTrunkInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ByocTrunkList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ByocTrunkList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ByocTrunks" + + def _create( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ByocTrunkInstance: + """ + Create the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The created ByocTrunkInstance + """ + payload, _, _ = self._create( + 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 ByocTrunkInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ByocTrunkInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + 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, + ) + instance = ByocTrunkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_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 ByocTrunkInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ByocTrunkInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_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, + ) + instance = ByocTrunkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ByocTrunkInstance]: + """ + Streams ByocTrunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ByocTrunkInstance]: + """ + Asynchronously streams ByocTrunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ByocTrunkInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ByocTrunkInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ByocTrunkInstance]: + """ + Lists ByocTrunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ByocTrunkInstance]: + """ + Asynchronously lists ByocTrunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ByocTrunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ByocTrunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ByocTrunkPage: + """ + Retrieve a single page of ByocTrunkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ByocTrunkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ByocTrunkPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ByocTrunkPage: + """ + Asynchronously retrieve a single page of ByocTrunkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ByocTrunkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ByocTrunkPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ByocTrunkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ByocTrunkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ByocTrunkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ByocTrunkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ByocTrunkPage: + """ + Retrieve a specific page of ByocTrunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ByocTrunkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ByocTrunkPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ByocTrunkPage: + """ + Asynchronously retrieve a specific page of ByocTrunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ByocTrunkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ByocTrunkPage(self._version, response) + + def get(self, sid: str) -> ByocTrunkContext: + """ + Constructs a ByocTrunkContext + + :param sid: The Twilio-provided string that uniquely identifies the BYOC Trunk resource to update. + """ + return ByocTrunkContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ByocTrunkContext: + """ + Constructs a ByocTrunkContext + + :param sid: The Twilio-provided string that uniquely identifies the BYOC Trunk resource to update. + """ + return ByocTrunkContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/voice/v1/connection_policy/__init__.py b/twilio/rest/voice/v1/connection_policy/__init__.py new file mode 100644 index 0000000000..2d8d1ac47e --- /dev/null +++ b/twilio/rest/voice/v1/connection_policy/__init__.py @@ -0,0 +1,1058 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.voice.v1.connection_policy.connection_policy_target import ( + ConnectionPolicyTargetList, +) + + +class ConnectionPolicyInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Connection Policy resource. + :ivar sid: The unique string that we created to identify the Connection Policy resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[ConnectionPolicyContext] = None + + @property + def _proxy(self) -> "ConnectionPolicyContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConnectionPolicyContext for this ConnectionPolicyInstance + """ + if self._context is None: + self._context = ConnectionPolicyContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ConnectionPolicyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectionPolicyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConnectionPolicyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectionPolicyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "ConnectionPolicyInstance": + """ + Fetch the ConnectionPolicyInstance + + + :returns: The fetched ConnectionPolicyInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConnectionPolicyInstance": + """ + Asynchronous coroutine to fetch the ConnectionPolicyInstance + + + :returns: The fetched ConnectionPolicyInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConnectionPolicyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConnectionPolicyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "ConnectionPolicyInstance": + """ + Update the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated ConnectionPolicyInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "ConnectionPolicyInstance": + """ + Asynchronous coroutine to update the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated ConnectionPolicyInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the ConnectionPolicyInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConnectionPolicyInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + + @property + def targets(self) -> ConnectionPolicyTargetList: + """ + Access the targets + """ + return self._proxy.targets + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConnectionPolicyContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ConnectionPolicyContext + + :param version: Version that contains the resource + :param sid: The unique string that we created to identify the Connection Policy resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/ConnectionPolicies/{sid}".format(**self._solution) + + self._targets: Optional[ConnectionPolicyTargetList] = None + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ConnectionPolicyInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConnectionPolicyInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectionPolicyInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectionPolicyInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConnectionPolicyInstance: + """ + Fetch the ConnectionPolicyInstance + + + :returns: The fetched ConnectionPolicyInstance + """ + payload, _, _ = self._fetch() + return ConnectionPolicyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConnectionPolicyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConnectionPolicyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConnectionPolicyInstance: + """ + Asynchronous coroutine to fetch the ConnectionPolicyInstance + + + :returns: The fetched ConnectionPolicyInstance + """ + payload, _, _ = await self._fetch_async() + return ConnectionPolicyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConnectionPolicyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConnectionPolicyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Update the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated ConnectionPolicyInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name) + return ConnectionPolicyInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the ConnectionPolicyInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = ConnectionPolicyInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Asynchronous coroutine to update the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated ConnectionPolicyInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) + return ConnectionPolicyInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConnectionPolicyInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = ConnectionPolicyInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def targets(self) -> ConnectionPolicyTargetList: + """ + Access the targets + """ + if self._targets is None: + self._targets = ConnectionPolicyTargetList( + self._version, + self._solution["sid"], + ) + return self._targets + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConnectionPolicyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConnectionPolicyInstance: + """ + Build an instance of ConnectionPolicyInstance + + :param payload: Payload response from the API + """ + + return ConnectionPolicyInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConnectionPolicyList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConnectionPolicyList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ConnectionPolicies" + + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Create the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The created ConnectionPolicyInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) + return ConnectionPolicyInstance(self._version, payload) + + def create_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the ConnectionPolicyInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = ConnectionPolicyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Asynchronously create the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The created ConnectionPolicyInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return ConnectionPolicyInstance(self._version, payload) + + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the ConnectionPolicyInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = ConnectionPolicyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConnectionPolicyInstance]: + """ + Streams ConnectionPolicyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConnectionPolicyInstance]: + """ + Asynchronously streams ConnectionPolicyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConnectionPolicyInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConnectionPolicyInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectionPolicyInstance]: + """ + Lists ConnectionPolicyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectionPolicyInstance]: + """ + Asynchronously lists ConnectionPolicyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConnectionPolicyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConnectionPolicyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectionPolicyPage: + """ + Retrieve a single page of ConnectionPolicyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectionPolicyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectionPolicyPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectionPolicyPage: + """ + Asynchronously retrieve a single page of ConnectionPolicyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectionPolicyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectionPolicyPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConnectionPolicyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConnectionPolicyPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConnectionPolicyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConnectionPolicyPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ConnectionPolicyPage: + """ + Retrieve a specific page of ConnectionPolicyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectionPolicyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConnectionPolicyPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConnectionPolicyPage: + """ + Asynchronously retrieve a specific page of ConnectionPolicyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectionPolicyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConnectionPolicyPage(self._version, response) + + def get(self, sid: str) -> ConnectionPolicyContext: + """ + Constructs a ConnectionPolicyContext + + :param sid: The unique string that we created to identify the Connection Policy resource to update. + """ + return ConnectionPolicyContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ConnectionPolicyContext: + """ + Constructs a ConnectionPolicyContext + + :param sid: The unique string that we created to identify the Connection Policy resource to update. + """ + return ConnectionPolicyContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/voice/v1/connection_policy/connection_policy_target.py b/twilio/rest/voice/v1/connection_policy/connection_policy_target.py new file mode 100644 index 0000000000..2f84ce2e4d --- /dev/null +++ b/twilio/rest/voice/v1/connection_policy/connection_policy_target.py @@ -0,0 +1,1323 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ConnectionPolicyTargetInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Target resource. + :ivar connection_policy_sid: The SID of the Connection Policy that owns the Target. + :ivar sid: The unique string that we created to identify the Target resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :ivar priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. + :ivar weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. + :ivar enabled: Whether the target is enabled. The default is `true`. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + connection_policy_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.connection_policy_sid: Optional[str] = payload.get("connection_policy_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.target: Optional[str] = payload.get("target") + self.priority: Optional[int] = deserialize.integer(payload.get("priority")) + self.weight: Optional[int] = deserialize.integer(payload.get("weight")) + self.enabled: Optional[bool] = payload.get("enabled") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "connection_policy_sid": connection_policy_sid, + "sid": sid or self.sid, + } + + self._context: Optional[ConnectionPolicyTargetContext] = None + + @property + def _proxy(self) -> "ConnectionPolicyTargetContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConnectionPolicyTargetContext for this ConnectionPolicyTargetInstance + """ + if self._context is None: + self._context = ConnectionPolicyTargetContext( + self._version, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ConnectionPolicyTargetInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectionPolicyTargetInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConnectionPolicyTargetInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectionPolicyTargetInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "ConnectionPolicyTargetInstance": + """ + Fetch the ConnectionPolicyTargetInstance + + + :returns: The fetched ConnectionPolicyTargetInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConnectionPolicyTargetInstance": + """ + Asynchronous coroutine to fetch the ConnectionPolicyTargetInstance + + + :returns: The fetched ConnectionPolicyTargetInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConnectionPolicyTargetInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConnectionPolicyTargetInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> "ConnectionPolicyTargetInstance": + """ + Update the ConnectionPolicyTargetInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: The updated ConnectionPolicyTargetInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> "ConnectionPolicyTargetInstance": + """ + Asynchronous coroutine to update the ConnectionPolicyTargetInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: The updated ConnectionPolicyTargetInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ConnectionPolicyTargetInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConnectionPolicyTargetInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConnectionPolicyTargetContext(InstanceContext): + + def __init__(self, version: Version, connection_policy_sid: str, sid: str): + """ + Initialize the ConnectionPolicyTargetContext + + :param version: Version that contains the resource + :param connection_policy_sid: The SID of the Connection Policy that owns the Target. + :param sid: The unique string that we created to identify the Target resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "connection_policy_sid": connection_policy_sid, + "sid": sid, + } + self._uri = "/ConnectionPolicies/{connection_policy_sid}/Targets/{sid}".format( + **self._solution + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ConnectionPolicyTargetInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConnectionPolicyTargetInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectionPolicyTargetInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectionPolicyTargetInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConnectionPolicyTargetInstance: + """ + Fetch the ConnectionPolicyTargetInstance + + + :returns: The fetched ConnectionPolicyTargetInstance + """ + payload, _, _ = self._fetch() + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConnectionPolicyTargetInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConnectionPolicyTargetInstance: + """ + Asynchronous coroutine to fetch the ConnectionPolicyTargetInstance + + + :returns: The fetched ConnectionPolicyTargetInstance + """ + payload, _, _ = await self._fetch_async() + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConnectionPolicyTargetInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Update the ConnectionPolicyTargetInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: The updated ConnectionPolicyTargetInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the ConnectionPolicyTargetInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + instance = ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Asynchronous coroutine to update the ConnectionPolicyTargetInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: The updated ConnectionPolicyTargetInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConnectionPolicyTargetInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + instance = ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 ConnectionPolicyTargetPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConnectionPolicyTargetInstance: + """ + Build an instance of ConnectionPolicyTargetInstance + + :param payload: Payload response from the API + """ + + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConnectionPolicyTargetList(ListResource): + + def __init__(self, version: Version, connection_policy_sid: str): + """ + Initialize the ConnectionPolicyTargetList + + :param version: Version that contains the resource + :param connection_policy_sid: The SID of the Connection Policy from which to read the Targets. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "connection_policy_sid": connection_policy_sid, + } + self._uri = "/ConnectionPolicies/{connection_policy_sid}/Targets".format( + **self._solution + ) + + def _create( + self, + target: str, + friendly_name: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + target: str, + friendly_name: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Create the ConnectionPolicyTargetInstance + + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. The default is `true`. + + :returns: The created ConnectionPolicyTargetInstance + """ + payload, _, _ = self._create( + target=target, + friendly_name=friendly_name, + priority=priority, + weight=weight, + enabled=enabled, + ) + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + ) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the ConnectionPolicyTargetInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + target=target, + friendly_name=friendly_name, + priority=priority, + weight=weight, + enabled=enabled, + ) + instance = ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + target: str, + friendly_name: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Asynchronously create the ConnectionPolicyTargetInstance + + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. The default is `true`. + + :returns: The created ConnectionPolicyTargetInstance + """ + payload, _, _ = await self._create_async( + target=target, + friendly_name=friendly_name, + priority=priority, + weight=weight, + enabled=enabled, + ) + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + ) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the ConnectionPolicyTargetInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + target=target, + friendly_name=friendly_name, + priority=priority, + weight=weight, + enabled=enabled, + ) + instance = ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConnectionPolicyTargetInstance]: + """ + Streams ConnectionPolicyTargetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConnectionPolicyTargetInstance]: + """ + Asynchronously streams ConnectionPolicyTargetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConnectionPolicyTargetInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConnectionPolicyTargetInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectionPolicyTargetInstance]: + """ + Lists ConnectionPolicyTargetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectionPolicyTargetInstance]: + """ + Asynchronously lists ConnectionPolicyTargetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConnectionPolicyTargetInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConnectionPolicyTargetInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectionPolicyTargetPage: + """ + Retrieve a single page of ConnectionPolicyTargetInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectionPolicyTargetInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectionPolicyTargetPage( + self._version, response, solution=self._solution + ) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectionPolicyTargetPage: + """ + Asynchronously retrieve a single page of ConnectionPolicyTargetInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectionPolicyTargetInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectionPolicyTargetPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConnectionPolicyTargetPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConnectionPolicyTargetPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConnectionPolicyTargetPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConnectionPolicyTargetPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ConnectionPolicyTargetPage: + """ + Retrieve a specific page of ConnectionPolicyTargetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectionPolicyTargetInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConnectionPolicyTargetPage( + self._version, response, solution=self._solution + ) + + async def get_page_async(self, target_url: str) -> ConnectionPolicyTargetPage: + """ + Asynchronously retrieve a specific page of ConnectionPolicyTargetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectionPolicyTargetInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConnectionPolicyTargetPage( + self._version, response, solution=self._solution + ) + + def get(self, sid: str) -> ConnectionPolicyTargetContext: + """ + Constructs a ConnectionPolicyTargetContext + + :param sid: The unique string that we created to identify the Target resource to update. + """ + return ConnectionPolicyTargetContext( + self._version, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ConnectionPolicyTargetContext: + """ + Constructs a ConnectionPolicyTargetContext + + :param sid: The unique string that we created to identify the Target resource to update. + """ + return ConnectionPolicyTargetContext( + self._version, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/voice/v1/dialing_permissions/__init__.py b/twilio/rest/voice/v1/dialing_permissions/__init__.py 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..fc4a80d633 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,161 @@ -# 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.api_response import ApiResponse + 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 + return "" - :returns: The created BulkCountryUpdateInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdateInstance + +class BulkCountryUpdateList(ListResource): + + def __init__(self, version: Version): """ - data = values.of({'UpdateRequest': update_request, }) + Initialize the BulkCountryUpdateList - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :param version: Version that contains the resource + + """ + super().__init__(version) - return BulkCountryUpdateInstance(self._version, payload, ) + self._uri = "/DialingPermissions/BulkCountryUpdates" - def __repr__(self): + def _create(self, update_request: str) -> tuple: """ - Provide a friendly representation + Internal helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + data = values.of( + { + "UpdateRequest": update_request, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -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. """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, response, solution): - """ - Initialize the BulkCountryUpdatePage + headers["Accept"] = "application/json" - :param Version version: Version that contains the resource - :param Response response: Response from the API + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdatePage - :rtype: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdatePage + def create(self, update_request: str) -> BulkCountryUpdateInstance: """ - super(BulkCountryUpdatePage, self).__init__(version, response) + Create the BulkCountryUpdateInstance - # Path Solution - self._solution = solution + :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\\\" } ]` - def get_instance(self, payload): + :returns: The created BulkCountryUpdateInstance """ - Build an instance of BulkCountryUpdateInstance + payload, _, _ = self._create(update_request=update_request) + return BulkCountryUpdateInstance(self._version, payload) - :param dict payload: Payload response from the API + def create_with_http_info(self, update_request: str) -> ApiResponse: + """ + Create the BulkCountryUpdateInstance and return response metadata + + :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.BulkCountryUpdateInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdateInstance + :returns: ApiResponse with instance, status code, and headers """ - return BulkCountryUpdateInstance(self._version, payload, ) + payload, status_code, headers = self._create(update_request=update_request) + instance = BulkCountryUpdateInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _create_async(self, update_request: str) -> tuple: """ - Provide a friendly representation + Internal async helper for create operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + data = values.of( + { + "UpdateRequest": update_request, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -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. """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, payload): - """ - Initialize the BulkCountryUpdateInstance + 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 - """ - super(BulkCountryUpdateInstance, self).__init__(version) + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - # Marshaled Properties - self._properties = { - 'update_count': deserialize.integer(payload.get('update_count')), - 'update_request': payload.get('update_request'), - } + async def create_async(self, update_request: str) -> BulkCountryUpdateInstance: + """ + Asynchronously create the BulkCountryUpdateInstance - # Context - self._context = None - self._solution = {} + :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\\\" } ]` - @property - def update_count(self): - """ - :returns: The number of countries updated - :rtype: unicode + :returns: The created BulkCountryUpdateInstance """ - return self._properties['update_count'] + payload, _, _ = await self._create_async(update_request=update_request) + return BulkCountryUpdateInstance(self._version, payload) - @property - def update_request(self): + async def create_with_http_info_async(self, update_request: str) -> ApiResponse: """ - :returns: A URL encoded JSON array of update objects - :rtype: unicode + Asynchronously create the BulkCountryUpdateInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers """ - return self._properties['update_request'] + payload, status_code, headers = await self._create_async( + update_request=update_request + ) + instance = BulkCountryUpdateInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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 46a7acf99c..ed666a1eb8 100644 --- a/twilio/rest/voice/v1/dialing_permissions/country/__init__.py +++ b/twilio/rest/voice/v1/dialing_permissions/country/__init__.py @@ -1,448 +1,933 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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. """ +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") - def __init__(self, version): - """ - Initialize the CountryList + self._solution = { + "iso_code": iso_code or self.iso_code, + } - :param Version version: Version that contains the resource + 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) - - # Path Solution - self._solution = {} - self._uri = '/DialingPermissions/Countries'.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, 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: CountryContext for this 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 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) + if self._context is None: + self._context = CountryContext( + self._version, + iso_code=self._solution["iso_code"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.voice.v1.dialing_permissions.country.CountryInstance] + def fetch(self) -> "CountryInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the CountryInstance - page = self.page( - iso_code=iso_code, - continent=continent, - country_code=country_code, - low_risk_numbers_enabled=low_risk_numbers_enabled, - high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, - high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched CountryInstance + """ + return self._proxy.fetch() - 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): + async def fetch_async(self) -> "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. + Asynchronous coroutine to 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. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - 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 """ - 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 await self._proxy.fetch_async() - 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): + def fetch_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of CountryInstance records from the API. - Request is executed immediately + Fetch the CountryInstance with HTTP info - :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 + :returns: ApiResponse with instance, status code, and headers """ - 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, - }) + return self._proxy.fetch_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info - return CountryPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with instance, status code, and headers """ - Retrieve a specific page of CountryInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_with_http_info_async() - :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 + @property + def highrisk_special_prefixes(self) -> HighriskSpecialPrefixList: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Access the highrisk_special_prefixes + """ + return self._proxy.highrisk_special_prefixes - return CountryPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, iso_code): + :returns: Machine friendly representation """ - Constructs a CountryContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param iso_code: The ISO country code +class CountryContext(InstanceContext): - :returns: twilio.rest.voice.v1.dialing_permissions.country.CountryContext - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryContext + def __init__(self, version: Version, iso_code: str): """ - return CountryContext(self._version, iso_code=iso_code, ) + Initialize the CountryContext - def __call__(self, iso_code): + :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 """ - Constructs a CountryContext + super().__init__(version) + + # Path Solution + self._solution = { + "iso_code": iso_code, + } + self._uri = "/DialingPermissions/Countries/{iso_code}".format(**self._solution) - :param iso_code: The ISO country code + self._highrisk_special_prefixes: Optional[HighriskSpecialPrefixList] = None - :returns: twilio.rest.voice.v1.dialing_permissions.country.CountryContext - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryContext + def _fetch(self) -> tuple: """ - return CountryContext(self._version, iso_code=iso_code, ) + Internal helper for fetch operation - def __repr__(self): + Returns: + tuple: (payload, status_code, headers) """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers = values.of({}) + headers["Accept"] = "application/json" -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 self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> CountryInstance: """ - Initialize the CountryPage + Fetch the CountryInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.voice.v1.dialing_permissions.country.CountryPage - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryPage + :returns: The fetched CountryInstance """ - super(CountryPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + payload, _, _ = self._fetch() + return CountryInstance( + self._version, + payload, + iso_code=self._solution["iso_code"], + ) - def get_instance(self, payload): + def fetch_with_http_info(self) -> ApiResponse: """ - Build an instance of CountryInstance + Fetch the CountryInstance and return response metadata - :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 + :returns: ApiResponse with instance, status code, and headers """ - return CountryInstance(self._version, payload, ) + payload, status_code, headers = self._fetch() + instance = CountryInstance( + self._version, + payload, + iso_code=self._solution["iso_code"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self): + async def _fetch_async(self) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation - :rtype: str + Returns: + tuple: (payload, status_code, headers) """ - return '' + headers = values.of({}) -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. """ - - def __init__(self, version, iso_code): - """ - Initialize the CountryContext + headers["Accept"] = "application/json" - :param Version version: Version that contains the resource - :param iso_code: The ISO country code + return await self._version.fetch_with_response_info_async( + 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 + async def fetch_async(self) -> CountryInstance: """ - super(CountryContext, self).__init__(version) - - # Path Solution - self._solution = {'iso_code': iso_code, } - self._uri = '/DialingPermissions/Countries/{iso_code}'.format(**self._solution) + Asynchronous coroutine to fetch the CountryInstance - # Dependents - self._highrisk_special_prefixes = None - def fetch(self): + :returns: The fetched CountryInstance """ - Fetch the CountryInstance + payload, _, _ = await self._fetch_async() + return CountryInstance( + self._version, + payload, + iso_code=self._solution["iso_code"], + ) - :returns: The fetched CountryInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance + async def fetch_with_http_info_async(self) -> ApiResponse: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronous coroutine to fetch the CountryInstance and return response metadata + - return CountryInstance(self._version, payload, iso_code=self._solution['iso_code'], ) + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CountryInstance( + self._version, + payload, + iso_code=self._solution["iso_code"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def highrisk_special_prefixes(self): + def highrisk_special_prefixes(self) -> HighriskSpecialPrefixList: """ Access the highrisk_special_prefixes - - :returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList - :rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList """ if self._highrisk_special_prefixes is None: self._highrisk_special_prefixes = HighriskSpecialPrefixList( self._version, - iso_code=self._solution['iso_code'], + self._solution["iso_code"], ) return self._highrisk_special_prefixes - def __repr__(self): + def __repr__(self) -> str: """ Provide 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 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'), - } - # Context - self._context = None - self._solution = {'iso_code': iso_code or self._properties['iso_code'], } +class CountryPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ - 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 CountryInstance - :returns: CountryContext for this CountryInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = CountryContext(self._version, iso_code=self._solution['iso_code'], ) - return self._context - @property - def iso_code(self): - """ - :returns: The ISO country code - :rtype: unicode + return CountryInstance(self._version, payload) + + def __repr__(self) -> str: """ - return self._properties['iso_code'] + Provide a friendly representation - @property - def name(self): + :returns: Machine friendly representation """ - :returns: The name of the country - :rtype: unicode + return "" + + +class CountryList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['name'] + Initialize the CountryList + + :param version: Version that contains the resource - @property - def continent(self): """ - :returns: The name of the continent in which the country is located - :rtype: unicode + super().__init__(version) + + self._uri = "/DialingPermissions/Countries" + + def stream( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: """ - return self._properties['continent'] + 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 country_codes(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 """ - :returns: The E.164 assigned country codes(s) - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = self.page( + iso_code=iso_code, + continent=continent, + country_code=country_code, + low_risk_numbers_enabled=low_risk_numbers_enabled, + high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, + high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: + """ + Asynchronously streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param str continent: Filter to retrieve the country permissions by specifying the continent + :param str country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['country_codes'] + 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"], + ) - @property - def low_risk_numbers_enabled(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams CountryInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - :returns: Whether dialing to low-risk numbers is enabled - :rtype: bool + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + 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"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams CountryInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['low_risk_numbers_enabled'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_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"], + ) - @property - def high_risk_special_numbers_enabled(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - :returns: Whether dialing to high-risk special services numbers is enabled - :rtype: bool + Lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param str continent: Filter to retrieve the country permissions by specifying the continent + :param str country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + iso_code=iso_code, + continent=continent, + country_code=country_code, + low_risk_numbers_enabled=low_risk_numbers_enabled, + high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, + high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Asynchronously lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param str continent: Filter to retrieve the country permissions by specifying the continent + :param str country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + iso_code=iso_code, + continent=continent, + country_code=country_code, + low_risk_numbers_enabled=low_risk_numbers_enabled, + high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, + high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists CountryInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + 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, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists CountryInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_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, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - return self._properties['high_risk_special_numbers_enabled'] + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately - @property - def high_risk_tollfraud_numbers_enabled(self): + :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 """ - :returns: Whether dialing to high-risk toll fraud numbers is enabled, else `false` - :rtype: bool + data = values.of( + { + "IsoCode": iso_code, + "Continent": continent, + "CountryCode": country_code, + "LowRiskNumbersEnabled": serialize.boolean_to_string( + low_risk_numbers_enabled + ), + "HighRiskSpecialNumbersEnabled": serialize.boolean_to_string( + high_risk_special_numbers_enabled + ), + "HighRiskTollfraudNumbersEnabled": serialize.boolean_to_string( + high_risk_tollfraud_numbers_enabled + ), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + async def page_async( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param continent: Filter to retrieve the country permissions by specifying the continent + :param country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance """ - return self._properties['high_risk_tollfraud_numbers_enabled'] + 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 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 CountryPage(self._version, response) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "IsoCode": iso_code, + "Continent": continent, + "CountryCode": country_code, + "LowRiskNumbersEnabled": serialize.boolean_to_string( + low_risk_numbers_enabled + ), + "HighRiskSpecialNumbersEnabled": serialize.boolean_to_string( + high_risk_special_numbers_enabled + ), + "HighRiskTollfraudNumbersEnabled": serialize.boolean_to_string( + high_risk_tollfraud_numbers_enabled + ), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "IsoCode": iso_code, + "Continent": continent, + "CountryCode": country_code, + "LowRiskNumbersEnabled": serialize.boolean_to_string( + low_risk_numbers_enabled + ), + "HighRiskSpecialNumbersEnabled": serialize.boolean_to_string( + high_risk_special_numbers_enabled + ), + "HighRiskTollfraudNumbersEnabled": serialize.boolean_to_string( + high_risk_tollfraud_numbers_enabled + ), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> CountryPage: """ - :returns: The absolute URL of this resource - :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['url'] + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) - @property - def links(self): + async def get_page_async(self, target_url: str) -> CountryPage: """ - :returns: A list of URLs related to this resource - :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['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 934cbec1a5..9e63e78d24 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,476 @@ -# 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.api_response import ApiResponse + from twilio.base.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"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[HighriskSpecialPrefixInstance]: + """ + Asynchronously streams HighriskSpecialPrefixInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - page = self.page(page_size=limits['page_size'], ) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams HighriskSpecialPrefixInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams HighriskSpecialPrefixInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - def list(self, limit=None, page_size=None): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[HighriskSpecialPrefixInstance]: """ Lists HighriskSpecialPrefixInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + 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] + :returns: list that will contain up to limit results """ - 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 list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[HighriskSpecialPrefixInstance]: """ - Retrieve a single page of HighriskSpecialPrefixInstance records from the API. - Request is executed immediately + Asynchronously lists HighriskSpecialPrefixInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :param str page_token: PageToken provided by the API - :param 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, }) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists HighriskSpecialPrefixInstance and returns headers from first page + - 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: ApiResponse with list of instances, status code, and headers """ - Retrieve a specific page of HighriskSpecialPrefixInstance records from the API. + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists HighriskSpecialPrefixInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - def __repr__(self): + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HighriskSpecialPrefixPage( + self._version, response, solution=self._solution + ) + + async def 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: """ - Provide a friendly representation + Asynchronously retrieve a single page of HighriskSpecialPrefixInstance records from the API. + Request is executed immediately - :returns: Machine friendly representation - :rtype: str + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of HighriskSpecialPrefixInstance """ - return '' + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -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. """ + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HighriskSpecialPrefixPage( + self._version, response, solution=self._solution + ) - def __init__(self, version, response, solution): + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Initialize the HighriskSpecialPrefixPage + Retrieve a single page with response metadata - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param iso_code: The ISO country code - :returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixPage - :rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixPage + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with HighriskSpecialPrefixPage, status code, and headers """ - super(HighriskSpecialPrefixPage, self).__init__(version, response) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - # Path Solution - self._solution = solution + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - def get_instance(self, payload): + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = HighriskSpecialPrefixPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - Build an instance of HighriskSpecialPrefixInstance + Asynchronously retrieve a single page with response metadata - :param dict payload: Payload response from the API - :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'], ) + :param page_token: PageToken provided by the 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: ApiResponse with HighriskSpecialPrefixPage, status code, and headers """ - Provide a friendly representation + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Accept"] = "application/json" -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. """ + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = HighriskSpecialPrefixPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - def __init__(self, version, payload, iso_code): + def get_page(self, target_url: str) -> HighriskSpecialPrefixPage: """ - Initialize the HighriskSpecialPrefixInstance + Retrieve a specific page of HighriskSpecialPrefixInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixInstance + :returns: Page of HighriskSpecialPrefixInstance """ - super(HighriskSpecialPrefixInstance, self).__init__(version) + response = self._version.domain.twilio.request("GET", target_url) + return HighriskSpecialPrefixPage( + self._version, response, solution=self._solution + ) - # Marshaled Properties - self._properties = {'prefix': payload.get('prefix'), } + async def get_page_async(self, target_url: str) -> HighriskSpecialPrefixPage: + """ + Asynchronously retrieve a specific page of HighriskSpecialPrefixInstance records from the API. + Request is executed immediately - # 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, solution=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..e1787b3ce5 100644 --- a/twilio/rest/voice/v1/dialing_permissions/settings.py +++ b/twilio/rest/voice/v1/dialing_permissions/settings.py @@ -1,242 +1,411 @@ -# 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.api_response import ApiResponse 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. """ +class SettingsInstance(InstanceResource): + """ + :ivar dialing_permissions_inheritance: `true` if the sub-account will inherit voice dialing permissions from the Master Project; otherwise `false`. + :ivar url: The absolute URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.dialing_permissions_inheritance: Optional[bool] = payload.get( + "dialing_permissions_inheritance" + ) + self.url: Optional[str] = payload.get("url") + + self._context: Optional[SettingsContext] = None - def __init__(self, version): + @property + def _proxy(self) -> "SettingsContext": """ - Initialize the SettingsList + 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: SettingsContext for this SettingsInstance + """ + if self._context is None: + self._context = SettingsContext( + self._version, + ) + return self._context - :returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsList - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsList + def fetch(self) -> "SettingsInstance": """ - super(SettingsList, self).__init__(version) + Fetch the SettingsInstance - # Path Solution - self._solution = {} - def get(self): + :returns: The fetched SettingsInstance """ - Constructs a SettingsContext + return self._proxy.fetch() - :returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext + async def fetch_async(self) -> "SettingsInstance": """ - return SettingsContext(self._version, ) + Asynchronous coroutine to fetch the SettingsInstance - def __call__(self): + + :returns: The fetched SettingsInstance """ - Constructs a SettingsContext + return await self._proxy.fetch_async() - :returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext + def fetch_with_http_info(self) -> ApiResponse: """ - return SettingsContext(self._version, ) + Fetch the SettingsInstance with HTTP info - def __repr__(self): + + :returns: ApiResponse with instance, status code, and headers """ - Provide a friendly representation + return self._proxy.fetch_with_http_info() - :returns: Machine friendly representation - :rtype: str + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SettingsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> "SettingsInstance": """ - return '' + Update the SettingsInstance + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. -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 updated SettingsInstance + """ + return self._proxy.update( + dialing_permissions_inheritance=dialing_permissions_inheritance, + ) - def __init__(self, version, response, solution): + async def update_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> "SettingsInstance": """ - Initialize the SettingsPage + Asynchronous coroutine to 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: The updated SettingsInstance + """ + return await self._proxy.update_async( + dialing_permissions_inheritance=dialing_permissions_inheritance, + ) - :returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsPage - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsPage + def update_with_http_info( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> ApiResponse: """ - super(SettingsPage, self).__init__(version, response) + Update the SettingsInstance with HTTP info - # Path Solution - self._solution = solution + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. - def get_instance(self, payload): + :returns: ApiResponse with instance, status code, and headers """ - Build an instance of SettingsInstance + return self._proxy.update_with_http_info( + dialing_permissions_inheritance=dialing_permissions_inheritance, + ) - :param dict payload: Payload response from the API + async def update_with_http_info_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SettingsInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers """ - return SettingsInstance(self._version, payload, ) + return await self._proxy.update_with_http_info_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 + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Settings" + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext + Returns: + tuple: (payload, status_code, headers) """ - super(SettingsContext, self).__init__(version) - # Path Solution - self._solution = {} - self._uri = '/Settings'.format(**self._solution) + headers = values.of({}) - def fetch(self): + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + 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, ) + payload, _, _ = self._fetch() + return SettingsInstance( + self._version, + payload, + ) - return SettingsInstance(self._version, payload, ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SettingsInstance and return response metadata - def update(self, dialing_permissions_inheritance=values.unset): + + :returns: ApiResponse with instance, status code, and headers """ - Update the SettingsInstance + payload, status_code, headers = self._fetch() + instance = SettingsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :param bool dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false` + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation - :returns: The updated SettingsInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance + Returns: + tuple: (payload, status_code, headers) """ - 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, ) + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) - def __repr__(self): + async def fetch_async(self) -> SettingsInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the SettingsInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched SettingsInstance """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + payload, _, _ = await self._fetch_async() + return SettingsInstance( + self._version, + payload, + ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SettingsInstance and return response metadata -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. """ - def __init__(self, version, payload): + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SettingsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> tuple: """ - Initialize the SettingsInstance + Internal helper for update operation - :returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance + Returns: + tuple: (payload, status_code, headers) """ - 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): + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> SettingsInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Update the SettingsInstance - :returns: SettingsContext for this SettingsInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: The updated SettingsInstance """ - if self._context is None: - self._context = SettingsContext(self._version, ) - return self._context + payload, _, _ = self._update( + dialing_permissions_inheritance=dialing_permissions_inheritance + ) + return SettingsInstance(self._version, payload) - @property - def dialing_permissions_inheritance(self): + def update_with_http_info( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> ApiResponse: """ - :returns: `true` if the sub-account will inherit voice dialing permissions from the Master Project; otherwise `false` - :rtype: bool + Update the SettingsInstance and return response metadata + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['dialing_permissions_inheritance'] + payload, status_code, headers = self._update( + dialing_permissions_inheritance=dialing_permissions_inheritance + ) + instance = SettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def url(self): + async def _update_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> tuple: """ - :returns: The absolute URL of this resource - :rtype: unicode + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['url'] - def fetch(self): + data = values.of( + { + "DialingPermissionsInheritance": serialize.boolean_to_string( + dialing_permissions_inheritance + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> SettingsInstance: """ - Fetch the SettingsInstance + Asynchronous coroutine to update the SettingsInstance - :returns: The fetched 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 """ - return self._proxy.fetch() + payload, _, _ = await self._update_async( + dialing_permissions_inheritance=dialing_permissions_inheritance + ) + return SettingsInstance(self._version, payload) - def update(self, dialing_permissions_inheritance=values.unset): + async def update_with_http_info_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> ApiResponse: """ - Update the SettingsInstance + Asynchronous coroutine to update the SettingsInstance and return response metadata - :param bool dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false` + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + dialing_permissions_inheritance=dialing_permissions_inheritance + ) + instance = SettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class SettingsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SettingsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> SettingsContext: + """ + Constructs a SettingsContext + + """ + return SettingsContext(self._version) + + def __call__(self) -> SettingsContext: + """ + Constructs a SettingsContext - :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 new file mode 100644 index 0000000000..9a17301f6d --- /dev/null +++ b/twilio/rest/voice/v1/ip_record.py @@ -0,0 +1,1076 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class IpRecordInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IP Record resource. + :ivar sid: The unique string that we created to identify the IP Record resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar ip_address: An IP address in dotted decimal notation, IPv4 only. + :ivar cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.ip_address: Optional[str] = payload.get("ip_address") + self.cidr_prefix_length: Optional[int] = deserialize.integer( + payload.get("cidr_prefix_length") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[IpRecordContext] = None + + @property + def _proxy(self) -> "IpRecordContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IpRecordContext for this IpRecordInstance + """ + if self._context is None: + self._context = IpRecordContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the IpRecordInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpRecordInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpRecordInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpRecordInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "IpRecordInstance": + """ + Fetch the IpRecordInstance + + + :returns: The fetched IpRecordInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IpRecordInstance": + """ + Asynchronous coroutine to fetch the IpRecordInstance + + + :returns: The fetched IpRecordInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpRecordInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpRecordInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "IpRecordInstance": + """ + Update the IpRecordInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated IpRecordInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "IpRecordInstance": + """ + Asynchronous coroutine to update the IpRecordInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated IpRecordInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the IpRecordInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IpRecordInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IpRecordContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the IpRecordContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/IpRecords/{sid}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the IpRecordInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpRecordInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpRecordInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpRecordInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpRecordInstance: + """ + Fetch the IpRecordInstance + + + :returns: The fetched IpRecordInstance + """ + payload, _, _ = self._fetch() + return IpRecordInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpRecordInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = IpRecordInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> IpRecordInstance: + """ + Asynchronous coroutine to fetch the IpRecordInstance + + + :returns: The fetched IpRecordInstance + """ + payload, _, _ = await self._fetch_async() + return IpRecordInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpRecordInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = IpRecordInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> IpRecordInstance: + """ + Update the IpRecordInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated IpRecordInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name) + return IpRecordInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the IpRecordInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = IpRecordInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> IpRecordInstance: + """ + Asynchronous coroutine to update the IpRecordInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated IpRecordInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) + return IpRecordInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IpRecordInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = IpRecordInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, 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 IpRecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IpRecordInstance: + """ + Build an instance of IpRecordInstance + + :param payload: Payload response from the API + """ + + return IpRecordInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class IpRecordList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the IpRecordList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/IpRecords" + + def _create( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpRecordInstance: + """ + Create the IpRecordInstance + + :param ip_address: An IP address in dotted decimal notation, IPv4 only. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + + :returns: The created IpRecordInstance + """ + payload, _, _ = self._create( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + return IpRecordInstance(self._version, payload) + + def create_with_http_info( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Create the IpRecordInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + instance = IpRecordInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpRecordInstance: + """ + Asynchronously create the IpRecordInstance + + :param ip_address: An IP address in dotted decimal notation, IPv4 only. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + + :returns: The created IpRecordInstance + """ + payload, _, _ = await self._create_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + return IpRecordInstance(self._version, payload) + + async def create_with_http_info_async( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the IpRecordInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + instance = IpRecordInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpRecordInstance]: + """ + Streams IpRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpRecordInstance]: + """ + Asynchronously streams IpRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams IpRecordInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams IpRecordInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpRecordInstance]: + """ + Lists IpRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpRecordInstance]: + """ + Asynchronously lists IpRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists IpRecordInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists IpRecordInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpRecordPage: + """ + Retrieve a single page of IpRecordInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpRecordInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpRecordPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpRecordPage: + """ + Asynchronously retrieve a single page of IpRecordInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpRecordInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpRecordPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpRecordPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IpRecordPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpRecordPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IpRecordPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> IpRecordPage: + """ + Retrieve a specific page of IpRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpRecordInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IpRecordPage(self._version, response) + + async def get_page_async(self, target_url: str) -> IpRecordPage: + """ + Asynchronously retrieve a specific page of IpRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpRecordInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpRecordPage(self._version, response) + + def get(self, sid: str) -> IpRecordContext: + """ + Constructs a IpRecordContext + + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + return IpRecordContext(self._version, sid=sid) + + def __call__(self, sid: str) -> IpRecordContext: + """ + Constructs a IpRecordContext + + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + return IpRecordContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/voice/v1/source_ip_mapping.py b/twilio/rest/voice/v1/source_ip_mapping.py new file mode 100644 index 0000000000..d4c30d09f5 --- /dev/null +++ b/twilio/rest/voice/v1/source_ip_mapping.py @@ -0,0 +1,1024 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SourceIpMappingInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the IP Record resource. + :ivar ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. + :ivar sip_domain_sid: The SID of the SIP Domain that the IP Record is mapped to. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.ip_record_sid: Optional[str] = payload.get("ip_record_sid") + self.sip_domain_sid: Optional[str] = payload.get("sip_domain_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[SourceIpMappingContext] = None + + @property + def _proxy(self) -> "SourceIpMappingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SourceIpMappingContext for this SourceIpMappingInstance + """ + if self._context is None: + self._context = SourceIpMappingContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SourceIpMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SourceIpMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SourceIpMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SourceIpMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "SourceIpMappingInstance": + """ + Fetch the SourceIpMappingInstance + + + :returns: The fetched SourceIpMappingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SourceIpMappingInstance": + """ + Asynchronous coroutine to fetch the SourceIpMappingInstance + + + :returns: The fetched SourceIpMappingInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SourceIpMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SourceIpMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update(self, sip_domain_sid: str) -> "SourceIpMappingInstance": + """ + Update the SourceIpMappingInstance + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The updated SourceIpMappingInstance + """ + return self._proxy.update( + sip_domain_sid=sip_domain_sid, + ) + + async def update_async(self, sip_domain_sid: str) -> "SourceIpMappingInstance": + """ + Asynchronous coroutine to update the SourceIpMappingInstance + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The updated SourceIpMappingInstance + """ + return await self._proxy.update_async( + sip_domain_sid=sip_domain_sid, + ) + + def update_with_http_info(self, sip_domain_sid: str) -> ApiResponse: + """ + Update the SourceIpMappingInstance with HTTP info + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + sip_domain_sid=sip_domain_sid, + ) + + async def update_with_http_info_async(self, sip_domain_sid: str) -> ApiResponse: + """ + Asynchronous coroutine to update the SourceIpMappingInstance with HTTP info + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + sip_domain_sid=sip_domain_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SourceIpMappingContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SourceIpMappingContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/SourceIpMappings/{sid}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the SourceIpMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SourceIpMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SourceIpMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SourceIpMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SourceIpMappingInstance: + """ + Fetch the SourceIpMappingInstance + + + :returns: The fetched SourceIpMappingInstance + """ + payload, _, _ = self._fetch() + return SourceIpMappingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SourceIpMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SourceIpMappingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SourceIpMappingInstance: + """ + Asynchronous coroutine to fetch the SourceIpMappingInstance + + + :returns: The fetched SourceIpMappingInstance + """ + payload, _, _ = await self._fetch_async() + return SourceIpMappingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SourceIpMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SourceIpMappingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, sip_domain_sid: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "SipDomainSid": sip_domain_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update(self, sip_domain_sid: str) -> SourceIpMappingInstance: + """ + Update the SourceIpMappingInstance + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The updated SourceIpMappingInstance + """ + payload, _, _ = self._update(sip_domain_sid=sip_domain_sid) + return SourceIpMappingInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def update_with_http_info(self, sip_domain_sid: str) -> ApiResponse: + """ + Update the SourceIpMappingInstance and return response metadata + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(sip_domain_sid=sip_domain_sid) + instance = SourceIpMappingInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, sip_domain_sid: str) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "SipDomainSid": sip_domain_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async(self, sip_domain_sid: str) -> SourceIpMappingInstance: + """ + Asynchronous coroutine to update the SourceIpMappingInstance + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The updated SourceIpMappingInstance + """ + payload, _, _ = await self._update_async(sip_domain_sid=sip_domain_sid) + return SourceIpMappingInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_async(self, sip_domain_sid: str) -> ApiResponse: + """ + Asynchronous coroutine to update the SourceIpMappingInstance and return response metadata + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + sip_domain_sid=sip_domain_sid + ) + instance = SourceIpMappingInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, 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 SourceIpMappingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SourceIpMappingInstance: + """ + Build an instance of SourceIpMappingInstance + + :param payload: Payload response from the API + """ + + return SourceIpMappingInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SourceIpMappingList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SourceIpMappingList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SourceIpMappings" + + def _create(self, ip_record_sid: str, sip_domain_sid: str) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, ip_record_sid: str, sip_domain_sid: str + ) -> SourceIpMappingInstance: + """ + Create the SourceIpMappingInstance + + :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The created SourceIpMappingInstance + """ + payload, _, _ = self._create( + ip_record_sid=ip_record_sid, sip_domain_sid=sip_domain_sid + ) + return SourceIpMappingInstance(self._version, payload) + + def create_with_http_info( + self, ip_record_sid: str, sip_domain_sid: str + ) -> ApiResponse: + """ + Create the SourceIpMappingInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + ip_record_sid=ip_record_sid, sip_domain_sid=sip_domain_sid + ) + instance = SourceIpMappingInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, ip_record_sid: str, sip_domain_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, ip_record_sid: str, sip_domain_sid: str + ) -> SourceIpMappingInstance: + """ + Asynchronously create the SourceIpMappingInstance + + :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The created SourceIpMappingInstance + """ + payload, _, _ = await self._create_async( + ip_record_sid=ip_record_sid, sip_domain_sid=sip_domain_sid + ) + return SourceIpMappingInstance(self._version, payload) + + async def create_with_http_info_async( + self, ip_record_sid: str, sip_domain_sid: str + ) -> ApiResponse: + """ + Asynchronously create the SourceIpMappingInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + ip_record_sid=ip_record_sid, sip_domain_sid=sip_domain_sid + ) + instance = SourceIpMappingInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SourceIpMappingInstance]: + """ + Streams SourceIpMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SourceIpMappingInstance]: + """ + Asynchronously streams SourceIpMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SourceIpMappingInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SourceIpMappingInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SourceIpMappingInstance]: + """ + Lists SourceIpMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SourceIpMappingInstance]: + """ + Asynchronously lists SourceIpMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SourceIpMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SourceIpMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SourceIpMappingPage: + """ + Retrieve a single page of SourceIpMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SourceIpMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SourceIpMappingPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SourceIpMappingPage: + """ + Asynchronously retrieve a single page of SourceIpMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SourceIpMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SourceIpMappingPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SourceIpMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SourceIpMappingPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SourceIpMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SourceIpMappingPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> SourceIpMappingPage: + """ + Retrieve a specific page of SourceIpMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SourceIpMappingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SourceIpMappingPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SourceIpMappingPage: + """ + Asynchronously retrieve a specific page of SourceIpMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SourceIpMappingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SourceIpMappingPage(self._version, response) + + def get(self, sid: str) -> SourceIpMappingContext: + """ + Constructs a SourceIpMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + return SourceIpMappingContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SourceIpMappingContext: + """ + Constructs a SourceIpMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + return SourceIpMappingContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/voice/v3/__init__.py b/twilio/rest/voice/v3/__init__.py new file mode 100644 index 0000000000..9d9bd3733b --- /dev/null +++ b/twilio/rest/voice/v3/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio API definition for public-api voice + Powers Twilio public-api voice + + NOTE: This 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.v3.transcription import TranscriptionList + + +class V3(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V3 version of Voice + + :param domain: The Twilio.voice domain + """ + super().__init__(domain, "v3") + self._transcriptions: Optional[TranscriptionList] = None + + @property + def transcriptions(self) -> TranscriptionList: + if self._transcriptions is None: + self._transcriptions = TranscriptionList(self) + return self._transcriptions + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/voice/v3/transcription.py b/twilio/rest/voice/v3/transcription.py new file mode 100644 index 0000000000..5ade4ce6fe --- /dev/null +++ b/twilio/rest/voice/v3/transcription.py @@ -0,0 +1,552 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio API definition for public-api voice + Powers Twilio public-api voice + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse +from twilio.base.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): + """ + :ivar operation_id: Unique identifier for the transcription operation. + :ivar status: Current status of the transcription operation. PENDING: accepted but not yet started. RUNNING: currently in progress. COMPLETED: successfully completed. FAILED: failed and cannot be completed. + :ivar status_url: URL to poll for the latest operation status. + :ivar transcription: + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + transcription_id: Optional[str] = None, + ): + super().__init__(version) + + self.operation_id: Optional[str] = payload.get("operationId") + self.status: Optional["TranscriptionInstance.str"] = payload.get("status") + self.status_url: Optional[str] = payload.get("statusUrl") + self.transcription: Optional[VoiceV3TranscriptionTranscription] = payload.get( + "transcription" + ) + + # Only set _solution if path params are provided (not None) + if transcription_id is not None: + self._solution = { + "transcription_id": transcription_id, + } + + 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, + transcription_id=self._solution["transcription_id"], + ) + return self._context + + def fetch(self) -> "TranscriptionInstance": + """ + Fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TranscriptionInstance": + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_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 TranscriptionContext(InstanceContext): + + def __init__(self, version: Version, transcription_id: str): + """ + Initialize the TranscriptionContext + + :param version: Version that contains the resource + :param transcription_id: The unique identifier of the transcription to fetch + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcription_id": transcription_id, + } + self._uri = "/Transcriptions/{transcription_id}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptionInstance: + """ + Fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + payload, _, _ = self._fetch() + return TranscriptionInstance( + self._version, + payload, + transcription_id=self._solution["transcription_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TranscriptionInstance( + self._version, + payload, + transcription_id=self._solution["transcription_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TranscriptionInstance: + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + payload, _, _ = await self._fetch_async() + return TranscriptionInstance( + self._version, + payload, + transcription_id=self._solution["transcription_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TranscriptionInstance( + self._version, + payload, + transcription_id=self._solution["transcription_id"], + ) + return ApiResponse(data=instance, status_code=status_code, 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 TranscriptionList(ListResource): + + class CreateV3TranscriptionsRequest(object): + """ + :ivar transcription_configuration_id: The ID of the transcription configuration to use + :ivar input_source: Discriminator indicating the input source type + :ivar source_id: The SID or TTID of the source audio to transcribe (e.g. a Twilio Recording SID). When provided, audioStartedAt is inferred from the recording's start time and does not need to be supplied by the caller. + :ivar participants: Participants in the conversation. If omitted or partially specified, defaults from the transcription configuration will be applied. + :ivar media_url: URL to the media file to transcribe + :ivar audio_started_at: The start time of the audio recording + """ + + def __init__(self, payload: Dict[str, Any]): + + self.transcription_configuration_id: Optional[str] = payload.get( + "transcriptionConfigurationId" + ) + self.input_source: Optional["TranscriptionInstance.str"] = payload.get( + "inputSource" + ) + self.source_id: Optional[str] = payload.get("sourceId") + self.participants: Optional[ + List[TranscriptionList.VoiceV3TranscriptionParticipant] + ] = payload.get("participants") + self.media_url: Optional[str] = payload.get("mediaUrl") + self.audio_started_at: Optional[datetime] = payload.get("audioStartedAt") + + def to_dict(self): + return { + "transcriptionConfigurationId": self.transcription_configuration_id, + "inputSource": self.input_source, + "sourceId": self.source_id, + "participants": ( + [participants.to_dict() for participants in self.participants] + if self.participants is not None + else None + ), + "mediaUrl": self.media_url, + "audioStartedAt": self.audio_started_at, + } + + class VoiceV3TranscriptionParticipant(object): + """ + :ivar type: The role of this participant in the conversation. + :ivar address: The phone number or identifier for this participant (E.164 format for phone numbers). Used to correlate this participant with their profile and conversation history. + :ivar name: User-defined name for this participant + :ivar audio_channel_index: One-based index of the audio channel in a multi-channel recording + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["TranscriptionInstance.str"] = payload.get("type") + self.address: Optional[str] = payload.get("address") + self.name: Optional[str] = payload.get("name") + self.audio_channel_index: Optional[int] = payload.get("audioChannelIndex") + + def to_dict(self): + return { + "type": self.type, + "address": self.address, + "name": self.name, + "audioChannelIndex": self.audio_channel_index, + } + + class VoiceV3TranscriptionResolvedConfiguration(object): + """ + :ivar transcription_engine: The engine used for transcription (Deepgram, Google, or auto) + :ivar speech_model: The speech model used for transcription (e.g., nova-2, nova-3, chirp_2) + :ivar language: The language code for transcription + :ivar transcription_status_callback: + :ivar conversation_configuration_id: Maestro conversation configuration ID + :ivar participant_defaults: Default participant configurations for the transcription + """ + + def __init__(self, payload: Dict[str, Any]): + + self.transcription_engine: Optional[str] = payload.get( + "transcriptionEngine" + ) + self.speech_model: Optional[str] = payload.get("speechModel") + self.language: Optional[str] = payload.get("language") + self.transcription_status_callback: Optional[ + VoiceV3TranscriptionTranscriptionStatusCallback + ] = payload.get("transcriptionStatusCallback") + self.conversation_configuration_id: Optional[str] = payload.get( + "conversationConfigurationId" + ) + self.participant_defaults: Optional[ + List[VoiceV3TranscriptionResolvedConfigurationParticipantDefaults] + ] = payload.get("participantDefaults") + + def to_dict(self): + return { + "transcriptionEngine": self.transcription_engine, + "speechModel": self.speech_model, + "language": self.language, + "transcriptionStatusCallback": ( + self.transcription_status_callback.to_dict() + if self.transcription_status_callback is not None + else None + ), + "conversationConfigurationId": self.conversation_configuration_id, + "participantDefaults": ( + [ + participant_defaults.to_dict() + for participant_defaults in self.participant_defaults + ] + if self.participant_defaults is not None + else None + ), + } + + class VoiceV3TranscriptionResolvedConfigurationParticipantDefaults(object): + """ + :ivar audio_channel_index: One-based index of the audio channel + :ivar type: The participant role type + """ + + def __init__(self, payload: Dict[str, Any]): + + self.audio_channel_index: Optional[int] = payload.get("audioChannelIndex") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "audioChannelIndex": self.audio_channel_index, + "type": self.type, + } + + class VoiceV3TranscriptionTranscriptionStatusCallback(object): + """ + :ivar url: The URL to call when transcription status changes + :ivar method: The HTTP method to use for the callback, currently only POST is supported + :ivar events: The transcription events that will trigger the callback + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional[str] = payload.get("method") + self.events: Optional[List[str]] = payload.get("events") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + "events": self.events, + } + + def __init__(self, version: Version): + """ + Initialize the TranscriptionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Transcriptions" + + def _create( + self, + create_v3_transcriptions_request: CreateV3TranscriptionsRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_v3_transcriptions_request.to_dict() + + headers = values.of( + { + "Idempotency-Key": idempotency_key, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + create_v3_transcriptions_request: CreateV3TranscriptionsRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> TranscriptionInstance: + """ + Create the TranscriptionInstance + + :param create_v3_transcriptions_request: + :param idempotency_key: A unique key to ensure idempotency. We recommend using UUID v7. Requests with the same key within the idempotency window return the original response. + + :returns: The created TranscriptionInstance + """ + payload, _, _ = self._create( + create_v3_transcriptions_request=create_v3_transcriptions_request, + idempotency_key=idempotency_key, + ) + return TranscriptionInstance(self._version, payload) + + def create_with_http_info( + self, + create_v3_transcriptions_request: CreateV3TranscriptionsRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the TranscriptionInstance and return response metadata + + :param create_v3_transcriptions_request: + :param idempotency_key: A unique key to ensure idempotency. We recommend using UUID v7. Requests with the same key within the idempotency window return the original response. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_v3_transcriptions_request=create_v3_transcriptions_request, + idempotency_key=idempotency_key, + ) + instance = TranscriptionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + create_v3_transcriptions_request: CreateV3TranscriptionsRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_v3_transcriptions_request.to_dict() + + headers = values.of( + { + "Idempotency-Key": idempotency_key, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + create_v3_transcriptions_request: CreateV3TranscriptionsRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> TranscriptionInstance: + """ + Asynchronously create the TranscriptionInstance + + :param create_v3_transcriptions_request: + :param idempotency_key: A unique key to ensure idempotency. We recommend using UUID v7. Requests with the same key within the idempotency window return the original response. + + :returns: The created TranscriptionInstance + """ + payload, _, _ = await self._create_async( + create_v3_transcriptions_request=create_v3_transcriptions_request, + idempotency_key=idempotency_key, + ) + return TranscriptionInstance(self._version, payload) + + async def create_with_http_info_async( + self, + create_v3_transcriptions_request: CreateV3TranscriptionsRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TranscriptionInstance and return response metadata + + :param create_v3_transcriptions_request: + :param idempotency_key: A unique key to ensure idempotency. We recommend using UUID v7. Requests with the same key within the idempotency window return the original response. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_v3_transcriptions_request=create_v3_transcriptions_request, + idempotency_key=idempotency_key, + ) + instance = TranscriptionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def get(self, transcription_id: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param transcription_id: The unique identifier of the transcription to fetch + """ + return TranscriptionContext(self._version, transcription_id=transcription_id) + + def __call__(self, transcription_id: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param transcription_id: The unique identifier of the transcription to fetch + """ + return TranscriptionContext(self._version, transcription_id=transcription_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/wireless/WirelessBase.py b/twilio/rest/wireless/WirelessBase.py new file mode 100644 index 0000000000..0228c4d666 --- /dev/null +++ b/twilio/rest/wireless/WirelessBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.wireless.v1 import V1 + + +class WirelessBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Wireless Domain + + :returns: Domain for Wireless + """ + super().__init__(twilio, "https://wireless.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Wireless + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/wireless/__init__.py b/twilio/rest/wireless/__init__.py index 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 7efb7e46c1..caad0d64b8 100644 --- a/twilio/rest/wireless/v1/command.py +++ b/twilio/rest/wireless/v1/command.py @@ -1,486 +1,1164 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): + """ + :ivar sid: The unique string that we created to identify the Command resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Command resource. + :ivar sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) that the Command was sent to or from. + :ivar command: The message being sent to or from the SIM. For text mode messages, this can be up to 160 characters. For binary mode messages, this is a series of up to 140 bytes of data encoded using base64. + :ivar command_mode: + :ivar transport: + :ivar delivery_receipt_requested: Whether to request a delivery receipt. + :ivar status: + :ivar direction: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.command: Optional[str] = payload.get("command") + self.command_mode: Optional["CommandInstance.CommandMode"] = payload.get( + "command_mode" + ) + self.transport: Optional["CommandInstance.Transport"] = payload.get("transport") + self.delivery_receipt_requested: Optional[bool] = payload.get( + "delivery_receipt_requested" + ) + self.status: Optional["CommandInstance.Status"] = payload.get("status") + self.direction: Optional["CommandInstance.Direction"] = payload.get("direction") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[CommandContext] = None + + @property + def _proxy(self) -> "CommandContext": """ - Streams CommandInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param unicode sim: The 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) + :returns: CommandContext for this CommandInstance + """ + if self._context is None: + self._context = CommandContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.command.CommandInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the CommandInstance - page = self.page( - sim=sim, - status=status, - direction=direction, - transport=transport, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, sim=values.unset, status=values.unset, direction=values.unset, - transport=values.unset, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists CommandInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the CommandInstance - :param unicode sim: The 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 await self._proxy.delete_async() - 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): + def delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of CommandInstance records from the API. - Request is executed immediately + Deletes the CommandInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers """ - data = values.of({ - 'Sim': sim, - 'Status': status, - 'Direction': direction, - 'Transport': transport, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.delete_with_http_info() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CommandInstance with HTTP info - return CommandPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: ApiResponse with success boolean, status code, and headers """ - 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 + return await self._proxy.delete_with_http_info_async() - :returns: Page of CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandPage + def fetch(self) -> "CommandInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Fetch the CommandInstance - return CommandPage(self._version, response, self._solution) - def create(self, command, 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: The fetched CommandInstance """ - Create the CommandInstance - - :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 + return self._proxy.fetch() - :returns: The created CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandInstance + async def fetch_async(self) -> "CommandInstance": """ - data = values.of({ - 'Command': command, - 'Sim': sim, - 'CallbackMethod': callback_method, - 'CallbackUrl': callback_url, - 'CommandMode': command_mode, - 'IncludeSid': include_sid, - 'DeliveryReceiptRequested': delivery_receipt_requested, - }) + Asynchronous coroutine to fetch the CommandInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return CommandInstance(self._version, payload, ) + :returns: The fetched CommandInstance + """ + return await self._proxy.fetch_async() - def get(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a CommandContext + Fetch the CommandInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return CommandContext(self._version, sid=sid, ) + return self._proxy.fetch_with_http_info() - def __call__(self, sid): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Constructs a CommandContext + Asynchronous coroutine to fetch the CommandInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return CommandContext(self._version, sid=sid, ) + return await self._proxy.fetch_with_http_info_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 CommandPage(Page): - """ """ +class CommandContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the CommandPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the CommandContext - :returns: twilio.rest.wireless.v1.command.CommandPage - :rtype: twilio.rest.wireless.v1.command.CommandPage + :param version: Version that contains the resource + :param sid: The SID of the Command resource to fetch. """ - super(CommandPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Commands/{sid}".format(**self._solution) - def get_instance(self, payload): + def _delete(self) -> tuple: """ - Build an instance of CommandInstance + Internal helper for delete operation - :param dict payload: Payload response from the API + Returns: + tuple: (success_boolean, status_code, headers) + """ - :returns: twilio.rest.wireless.v1.command.CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandInstance + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return CommandInstance(self._version, payload, ) + Deletes the CommandInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the CommandInstance and return response metadata -class CommandContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: """ - Initialize the CommandContext + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CommandInstance - :param Version version: Version that contains the resource - :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 """ - super(CommandContext, self).__init__(version) + success, _, _ = await self._delete_async() + return success - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Commands/{sid}'.format(**self._solution) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CommandInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - def fetch(self): + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CommandInstance: """ Fetch the CommandInstance + :returns: The fetched CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CommandInstance and return response metadata - return CommandInstance(self._version, payload, sid=self._solution['sid'], ) - def delete(self): + :returns: ApiResponse with instance, status code, and headers """ - Deletes the CommandInstance + payload, status_code, headers = self._fetch() + instance = CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def _fetch_async(self) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal async helper for fetch operation - def __repr__(self): + Returns: + tuple: (payload, status_code, headers) """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CommandInstance: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Asynchronous coroutine to fetch the CommandInstance -class CommandInstance(InstanceResource): - """ """ + :returns: The fetched CommandInstance + """ + payload, _, _ = await self._fetch_async() + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - class Direction(object): - FROM_SIM = "from_sim" - TO_SIM = "to_sim" + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CommandInstance and return response metadata - class Status(object): - QUEUED = "queued" - SENT = "sent" - DELIVERED = "delivered" - RECEIVED = "received" - FAILED = "failed" - class CommandMode(object): - TEXT = "text" - BINARY = "binary" + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - class Transport(object): - SMS = "sms" - IP = "ip" + def __repr__(self) -> str: + """ + Provide a friendly representation - 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'), - } + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): +class CommandPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CommandInstance: """ - 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 CommandInstance - :returns: CommandContext for this CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = CommandContext(self._version, sid=self._solution['sid'], ) - return self._context - @property - def sid(self): + return CommandInstance(self._version, payload) + + def __repr__(self) -> str: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['sid'] + return "" - @property - def account_sid(self): + +class CommandList(ListResource): + + def __init__(self, version: Version): """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Initialize the CommandList + + :param version: Version that contains the resource + """ - return self._properties['account_sid'] + super().__init__(version) - @property - def sim_sid(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, + ) -> tuple: """ - :returns: The SID of the Sim resource that the Command was sent to or from - :rtype: unicode + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._properties['sim_sid'] - @property - def command(self): + data = values.of( + { + "Command": command, + "Sim": sim, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "CommandMode": command_mode, + "IncludeSid": include_sid, + "DeliveryReceiptRequested": serialize.boolean_to_string( + delivery_receipt_requested + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - :returns: The message being sent to or from the SIM - :rtype: unicode + Create the CommandInstance + + :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. + :param callback_method: The HTTP method we use to call `callback_url`. Can be: `POST` or `GET`, and the default is `POST`. + :param callback_url: The URL we call using the `callback_url` when the Command has finished sending, whether the command was delivered or it failed. + :param command_mode: + :param include_sid: Whether to include the SID of the command in the message body. Can be: `none`, `start`, or `end`, and the default behavior is `none`. When sending a Command to a SIM in text mode, we can automatically include the SID of the Command in the message body, which could be used to ensure that the device does not process the same Command more than once. A value of `start` will prepend the message with the Command SID, and `end` will append it to the end, separating the Command SID from the message body with a space. The length of the Command SID is included in the 160 character limit so the SMS body must be 128 characters or less before the Command SID is included. + :param delivery_receipt_requested: Whether to request delivery receipt from the recipient. For Commands that request delivery receipt, the Command state transitions to 'delivered' once the server has received a delivery receipt from the device. The default value is `true`. + + :returns: The created CommandInstance """ - return self._properties['command'] + payload, _, _ = self._create( + command=command, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + delivery_receipt_requested=delivery_receipt_requested, + ) + return CommandInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the CommandInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + command=command, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + delivery_receipt_requested=delivery_receipt_requested, + ) + instance = CommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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"}) - @property - def command_mode(self): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + command: str, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union["CommandInstance.CommandMode", object] = values.unset, + include_sid: Union[str, object] = values.unset, + delivery_receipt_requested: Union[bool, object] = values.unset, + ) -> CommandInstance: + """ + Asynchronously create the CommandInstance + + :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. + :param callback_method: The HTTP method we use to call `callback_url`. Can be: `POST` or `GET`, and the default is `POST`. + :param callback_url: The URL we call using the `callback_url` when the Command has finished sending, whether the command was delivered or it failed. + :param command_mode: + :param include_sid: Whether to include the SID of the command in the message body. Can be: `none`, `start`, or `end`, and the default behavior is `none`. When sending a Command to a SIM in text mode, we can automatically include the SID of the Command in the message body, which could be used to ensure that the device does not process the same Command more than once. A value of `start` will prepend the message with the Command SID, and `end` will append it to the end, separating the Command SID from the message body with a space. The length of the Command SID is included in the 160 character limit so the SMS body must be 128 characters or less before the Command SID is included. + :param delivery_receipt_requested: Whether to request delivery receipt from the recipient. For Commands that request delivery receipt, the Command state transitions to 'delivered' once the server has received a delivery receipt from the device. The default value is `true`. + + :returns: The created CommandInstance """ - :returns: The mode used to send the SMS message - :rtype: CommandInstance.CommandMode + payload, _, _ = await self._create_async( + command=command, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + delivery_receipt_requested=delivery_receipt_requested, + ) + return CommandInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the CommandInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + command=command, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + delivery_receipt_requested=delivery_receipt_requested, + ) + instance = CommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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]: """ - return self._properties['command_mode'] + 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 transport(self): + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The type of transport used - :rtype: CommandInstance.Transport + limits = self._version.read_limits(limit, page_size) + page = self.page( + sim=sim, + status=status, + direction=direction, + transport=transport, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CommandInstance]: """ - 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): + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: Whether to request a delivery receipt - :rtype: bool + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sim=sim, + status=status, + direction=direction, + transport=transport, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: """ - return self._properties['delivery_receipt_requested'] + Streams CommandInstance and returns headers from first page - @property - def status(self): + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sim=sim, + status=status, + direction=direction, + transport=transport, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: """ - :returns: The status of the Command - :rtype: CommandInstance.Status + Asynchronously streams CommandInstance and returns headers from first page + + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['status'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sim=sim, + status=status, + direction=direction, + transport=transport, + page_size=limits["page_size"], + ) - @property - def direction(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists CommandInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sim=sim, + status=status, + direction=direction, + transport=transport, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists CommandInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sim=sim, + status=status, + direction=direction, + transport=transport, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with CommandPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with CommandPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 098b0d1538..77742cf2ba 100644 --- a/twilio/rest/wireless/v1/rate_plan.py +++ b/twilio/rest/wireless/v1/rate_plan.py @@ -1,512 +1,1309 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.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): - """ """ +class RatePlanInstance(InstanceResource): + + class DataLimitStrategy(object): + BLOCK = "block" + THROTTLE = "throttle" + + """ + :ivar sid: The unique string that we created to identify the RatePlan resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RatePlan resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar data_enabled: Whether SIMs can use GPRS/3G/4G/LTE data connectivity. + :ivar data_metering: The model used to meter data usage. Can be: `payg` and `quota-1`, `quota-10`, and `quota-50`. Learn more about the available [data metering models](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#payg-vs-quota-data-plans). + :ivar data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on the home network (T-Mobile USA). The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. + :ivar messaging_enabled: Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :ivar voice_enabled: Deprecated. Whether SIMs can make and receive voice calls. + :ivar national_roaming_enabled: Whether SIMs can roam on networks other than the home network (T-Mobile USA) in the United States. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming). + :ivar national_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. + :ivar international_roaming: The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. + :ivar international_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.data_enabled: Optional[bool] = payload.get("data_enabled") + self.data_metering: Optional[str] = payload.get("data_metering") + self.data_limit: Optional[int] = deserialize.integer(payload.get("data_limit")) + self.messaging_enabled: Optional[bool] = payload.get("messaging_enabled") + self.voice_enabled: Optional[bool] = payload.get("voice_enabled") + self.national_roaming_enabled: Optional[bool] = payload.get( + "national_roaming_enabled" + ) + self.national_roaming_data_limit: Optional[int] = deserialize.integer( + payload.get("national_roaming_data_limit") + ) + self.international_roaming: Optional[List[str]] = payload.get( + "international_roaming" + ) + self.international_roaming_data_limit: Optional[int] = deserialize.integer( + payload.get("international_roaming_data_limit") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } - def __init__(self, version): + 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.wireless.v1.rate_plan.RatePlanList - :rtype: twilio.rest.wireless.v1.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. + 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 RatePlanInstance - :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 """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RatePlanInstance with HTTP info - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: ApiResponse with success boolean, status code, and headers """ - Lists RatePlanInstance 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.delete_with_http_info() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is 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 delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RatePlanInstance with HTTP info - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.rate_plan.RatePlanInstance] + + :returns: ApiResponse with success boolean, status code, and headers """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_with_http_info_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "RatePlanInstance": """ - Retrieve a single page of RatePlanInstance records from the API. - Request is executed immediately + Fetch the RatePlanInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanPage + :returns: The fetched RatePlanInstance """ - 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) -> "RatePlanInstance": + """ + Asynchronous coroutine to fetch the RatePlanInstance - return RatePlanPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched RatePlanInstance """ - Retrieve a specific page of RatePlanInstance 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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RatePlanInstance with HTTP info - :returns: Page of RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanPage + + :returns: ApiResponse with instance, status code, and headers """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RatePlanInstance with HTTP info - return RatePlanPage(self._version, response, self._solution) - def create(self, unique_name=values.unset, friendly_name=values.unset, - data_enabled=values.unset, data_limit=values.unset, - data_metering=values.unset, messaging_enabled=values.unset, - voice_enabled=values.unset, national_roaming_enabled=values.unset, - international_roaming=values.unset, - national_roaming_data_limit=values.unset, - international_roaming_data_limit=values.unset): + :returns: ApiResponse with instance, status code, and headers """ - Create the RatePlanInstance + return await self._proxy.fetch_with_http_info_async() + + 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 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 + :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 created RatePlanInstance - :rtype: twilio.rest.wireless.v1.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, - 'NationalRoamingEnabled': national_roaming_enabled, - 'InternationalRoaming': serialize.map(international_roaming, lambda e: e), - 'NationalRoamingDataLimit': national_roaming_data_limit, - 'InternationalRoamingDataLimit': international_roaming_data_limit, - }) + return self._proxy.update( + unique_name=unique_name, + friendly_name=friendly_name, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": + """ + Asynchronous coroutine to update the RatePlanInstance - return RatePlanInstance(self._version, payload, ) + :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. - def get(self, sid): + :returns: The updated RatePlanInstance """ - Constructs a RatePlanContext + return await self._proxy.update_async( + unique_name=unique_name, + friendly_name=friendly_name, + ) - :param sid: The SID that identifies the resource to fetch + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RatePlanInstance with HTTP info - :returns: twilio.rest.wireless.v1.rate_plan.RatePlanContext - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanContext + :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: ApiResponse with instance, status code, and headers """ - return RatePlanContext(self._version, sid=sid, ) + return self._proxy.update_with_http_info( + unique_name=unique_name, + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Constructs a RatePlanContext + Asynchronous coroutine to update the RatePlanInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return RatePlanContext(self._version, sid=sid, ) + return await self._proxy.update_with_http_info_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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ - Build an instance of RatePlanInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.wireless.v1.rate_plan.RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanInstance + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - return RatePlanInstance(self._version, payload, ) + Deletes the RatePlanInstance - def __repr__(self): + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + success, _, _ = self._delete() + return success - :returns: Machine friendly representation - :rtype: str + def delete_with_http_info(self) -> ApiResponse: """ - return '' + Deletes the RatePlanInstance and return response metadata -class RatePlanContext(InstanceContext): - """ """ + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def __init__(self, version, sid): + async def _delete_async(self) -> tuple: """ - Initialize the RatePlanContext + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.wireless.v1.rate_plan.RatePlanContext - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanContext + async def delete_async(self) -> bool: """ - super(RatePlanContext, self).__init__(version) + Asynchronous coroutine that deletes the RatePlanInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RatePlans/{sid}'.format(**self._solution) - def fetch(self): + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RatePlanInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RatePlanInstance: """ Fetch the RatePlanInstance + :returns: The fetched RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload, _, _ = self._fetch() + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - return RatePlanInstance(self._version, payload, sid=self._solution['sid'], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RatePlanInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def update(self, unique_name=values.unset, friendly_name=values.unset): + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RatePlanInstance: + """ + Asynchronous coroutine to fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + payload, _, _ = await self._fetch_async() + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RatePlanInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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._update( + unique_name=unique_name, friendly_name=friendly_name + ) + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RatePlanInstance and return response metadata - return RatePlanInstance(self._version, payload, sid=self._solution['sid'], ) + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. - def delete(self): + :returns: ApiResponse with instance, status code, and headers """ - Deletes the RatePlanInstance + payload, status_code, headers = self._update( + unique_name=unique_name, friendly_name=friendly_name + ) + instance = RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def _update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Internal async helper for update operation - def __repr__(self): + Returns: + tuple: (payload, status_code, headers) """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Asynchronous coroutine to update the RatePlanInstance + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. -class RatePlanInstance(InstanceResource): - """ """ + :returns: The updated RatePlanInstance + """ + payload, _, _ = await self._update_async( + unique_name=unique_name, friendly_name=friendly_name + ) + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) - class DataLimitStrategy(object): - BLOCK = "block" - THROTTLE = "throttle" + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RatePlanInstance and return response metadata - 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'), - } + :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. - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + unique_name=unique_name, friendly_name=friendly_name + ) + instance = RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @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): + +class RatePlanPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RatePlanInstance: """ - :returns: The unique string that identifies the resource - :rtype: unicode + Build an instance of RatePlanInstance + + :param payload: Payload response from the API """ - return self._properties['sid'] - @property - def unique_name(self): + return RatePlanInstance(self._version, payload) + + def __repr__(self) -> str: """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def account_sid(self): + +class RatePlanList(ListResource): + + def __init__(self, version: Version): """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Initialize the RatePlanList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RatePlans" + + def _create( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + national_roaming_data_limit: Union[int, object] = values.unset, + international_roaming_data_limit: Union[int, object] = values.unset, + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['account_sid'] + Create the RatePlanInstance - @property - def friendly_name(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: The string that you assigned to describe the resource - :rtype: unicode + payload, _, _ = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + national_roaming_data_limit=national_roaming_data_limit, + international_roaming_data_limit=international_roaming_data_limit, + data_limit_strategy=data_limit_strategy, + ) + return RatePlanInstance(self._version, payload) + + def create_with_http_info( + 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, + ) -> ApiResponse: + """ + Create the RatePlanInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + national_roaming_data_limit=national_roaming_data_limit, + international_roaming_data_limit=international_roaming_data_limit, + data_limit_strategy=data_limit_strategy, + ) + instance = RatePlanInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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['friendly_name'] + payload, _, _ = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + national_roaming_data_limit=national_roaming_data_limit, + international_roaming_data_limit=international_roaming_data_limit, + data_limit_strategy=data_limit_strategy, + ) + return RatePlanInstance(self._version, payload) + + async def create_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously create the RatePlanInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + national_roaming_data_limit=national_roaming_data_limit, + international_roaming_data_limit=international_roaming_data_limit, + data_limit_strategy=data_limit_strategy, + ) + instance = RatePlanInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def data_enabled(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RatePlanInstance]: """ - :returns: Whether SIMs can use GPRS/3G/4G/LTE data connectivity - :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['data_enabled'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def data_metering(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 model used to meter data usage - :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['data_metering'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def data_limit(self): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: The total data usage in Megabytes that the Network allows during one month on the home network - :rtype: unicode + Streams RatePlanInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['data_limit'] + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - @property - def messaging_enabled(self): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - :returns: Whether SIMs can make, send, and receive SMS using Commands - :rtype: bool + Asynchronously streams RatePlanInstance and returns headers from first 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) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - return self._properties['messaging_enabled'] + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) - @property - def voice_enabled(self): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RatePlanInstance]: """ - :returns: Whether SIMs can make and receive voice calls - :rtype: 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. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['voice_enabled'] - @property - def national_roaming_enabled(self): + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RatePlanInstance]: """ - :returns: Whether SIMs can roam on networks other than the home network in the United States - :rtype: bool + 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 self._properties['national_roaming_enabled'] - @property - def national_roaming_data_limit(self): + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The total data usage in Megabytes that the Network allows during one month on non-home networks in the United States - :rtype: unicode + Lists RatePlanInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['national_roaming_data_limit'] + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def international_roaming(self): + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - :returns: The services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States - :rtype: unicode + Asynchronously lists RatePlanInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['international_roaming'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def international_roaming_data_limit(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, + ) -> RatePlanPage: """ - :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 + Retrieve a single page of RatePlanInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RatePlanInstance """ - return self._properties['international_roaming_data_limit'] + 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 RatePlanPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RatePlanPage: + """ + Asynchronously retrieve a single page of RatePlanInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RatePlanInstance """ - :returns: The date when the resource was created, 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RatePlanPage(self._version, response) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_created'] + Retrieve a single page with response metadata - @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: ApiResponse with RatePlanPage, status code, and headers """ - :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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RatePlanPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page with response metadata - @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: ApiResponse with RatePlanPage, status code, and headers """ - :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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RatePlanPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 - 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: 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 d8ad2e9257..33fee1d428 100644 --- a/twilio/rest/wireless/v1/sim/__init__.py +++ b/twilio/rest/wireless/v1/sim/__init__.py @@ -1,732 +1,1697 @@ -# 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.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource 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" + + class Status(object): + NEW = "new" + READY = "ready" + ACTIVE = "active" + SUSPENDED = "suspended" + DEACTIVATED = "deactivated" + CANCELED = "canceled" + SCHEDULED = "scheduled" + UPDATING = "updating" - :param Version version: Version that contains the resource + """ + :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") - :returns: twilio.rest.wireless.v1.sim.SimList - :rtype: twilio.rest.wireless.v1.sim.SimList - """ - super(SimList, self).__init__(version) + self._solution = { + "sid": sid or self.sid, + } - # Path Solution - self._solution = {} - self._uri = '/Sims'.format(**self._solution) + 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'], limits['page_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 delete_with_http_info(self) -> ApiResponse: """ - Retrieve a single page of SimInstance records from the API. - Request is executed immediately + Deletes the SimInstance with HTTP info - :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: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: """ - 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, - }) + Asynchronous coroutine that deletes the SimInstance with HTTP info - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return SimPage(self._version, response, self._solution) + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() - def get_page(self, target_url): + def fetch(self) -> "SimInstance": """ - Retrieve a specific page of SimInstance records from the API. - Request is executed immediately + Fetch the SimInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimPage + :returns: The fetched SimInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return SimPage(self._version, response, self._solution) + return self._proxy.fetch() - def get(self, sid): + async def fetch_async(self) -> "SimInstance": """ - Constructs a SimContext + Asynchronous coroutine to fetch the SimInstance - :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: The fetched SimInstance """ - return SimContext(self._version, sid=sid, ) + return await self._proxy.fetch_async() - def __call__(self, sid): + def fetch_with_http_info(self) -> ApiResponse: """ - Constructs a SimContext + Fetch the SimInstance with HTTP info - :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: ApiResponse with instance, status code, and headers """ - return SimContext(self._version, sid=sid, ) + return self._proxy.fetch_with_http_info() - def __repr__(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the SimInstance with HTTP info - :returns: Machine friendly representation - :rtype: str + + :returns: ApiResponse with instance, status code, and headers """ - return '' + return await self._proxy.fetch_with_http_info_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 -class SimPage(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). - def __init__(self, version, response, solution): + :returns: The updated SimInstance """ - Initialize the SimPage + 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, + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API + 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: twilio.rest.wireless.v1.sim.SimPage - :rtype: twilio.rest.wireless.v1.sim.SimPage + :returns: The updated SimInstance """ - super(SimPage, self).__init__(version, response) + 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, + ) - # Path Solution - self._solution = solution + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the SimInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + reset_status=reset_status, + account_sid=account_sid, + ) - def get_instance(self, payload): - """ - Build an instance of SimInstance + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SimInstance with HTTP info + + :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: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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, + ) - :param dict payload: Payload response from the API + @property + def data_sessions(self) -> DataSessionList: + """ + Access the data_sessions + """ + return self._proxy.data_sessions - :returns: twilio.rest.wireless.v1.sim.SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimInstance + @property + def usage_records(self) -> UsageRecordList: + """ + Access the usage_records """ - return SimInstance(self._version, payload, ) + 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 SimContext(InstanceContext): - """ """ - def __init__(self, version, sid): + def __init__(self, version: Version, sid: str): """ Initialize the SimContext - :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 + :param version: Version that contains the resource + :param sid: The SID or the `unique_name` of the Sim resource to update. """ - super(SimContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Sims/{sid}'.format(**self._solution) + self._solution = { + "sid": sid, + } + self._uri = "/Sims/{sid}".format(**self._solution) - # Dependents - self._usage_records = None - self._data_sessions = None + self._data_sessions: Optional[DataSessionList] = None + self._usage_records: Optional[UsageRecordList] = None - def fetch(self): + def _delete(self) -> tuple: """ - Fetch the SimInstance + Internal helper for delete operation - :returns: The fetched SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - 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, 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 = values.of({}) - :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 + return self._version.delete_with_response_info( + method="DELETE", 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): + def delete(self) -> bool: """ Deletes the SimInstance + :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + success, _, _ = self._delete() + return success - @property - def usage_records(self): + def delete_with_http_info(self) -> ApiResponse: """ - Access the usage_records + Deletes the SimInstance and return response metadata - :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList - """ - if self._usage_records is None: - self._usage_records = UsageRecordList(self._version, sim_sid=self._solution['sid'], ) - return self._usage_records - @property - def data_sessions(self): + :returns: ApiResponse with success boolean, status code, and headers """ - Access the data_sessions + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :returns: twilio.rest.wireless.v1.sim.data_session.DataSessionList - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionList + async def _delete_async(self) -> tuple: """ - if self._data_sessions is None: - self._data_sessions = DataSessionList(self._version, sim_sid=self._solution['sid'], ) - return self._data_sessions + Internal async helper for delete operation - def __repr__(self): + Returns: + tuple: (success_boolean, status_code, headers) """ - Provide 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({}) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) -class SimInstance(InstanceResource): - """ """ + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SimInstance - class Status(object): - NEW = "new" - READY = "ready" - ACTIVE = "active" - SUSPENDED = "suspended" - DEACTIVATED = "deactivated" - CANCELED = "canceled" - SCHEDULED = "scheduled" - UPDATING = "updating" - class ResetStatus(object): - RESETTING = "resetting" + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success - 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'), - } + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SimInstance and return response metadata - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): + :returns: ApiResponse with success boolean, status code, and headers """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :returns: SimContext for this SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimContext + def _fetch(self) -> tuple: """ - if self._context is None: - self._context = SimContext(self._version, sid=self._solution['sid'], ) - return self._context + Internal helper for fetch operation - @property - def sid(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The unique string that identifies the Sim 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'] + headers = values.of({}) - @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'] + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - @property - def friendly_name(self): + def fetch(self) -> SimInstance: """ - :returns: The string that you assigned to describe the Sim resource - :rtype: unicode - """ - return self._properties['friendly_name'] + Fetch the SimInstance - @property - def iccid(self): - """ - :returns: The ICCID associated with the SIM - :rtype: unicode - """ - return self._properties['iccid'] - @property - def e_id(self): - """ - :returns: Deprecated - :rtype: unicode + :returns: The fetched SimInstance """ - return self._properties['e_id'] + payload, _, _ = self._fetch() + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - @property - def status(self): + def fetch_with_http_info(self) -> ApiResponse: """ - :returns: The status of the Sim resource - :rtype: SimInstance.Status - """ - return self._properties['status'] + Fetch the SimInstance and return response metadata - @property - def reset_status(self): - """ - :returns: The connectivity reset status of the SIM - :rtype: SimInstance.ResetStatus - """ - return self._properties['reset_status'] - @property - def commands_callback_url(self): - """ - :returns: The URL we call when the SIM originates a machine-to-machine Command - :rtype: unicode + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['commands_callback_url'] + payload, status_code, headers = self._fetch() + instance = SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - @property - def commands_callback_method(self): + async def _fetch_async(self) -> tuple: """ - :returns: The HTTP method we use to call commands_callback_url - :rtype: unicode - """ - return self._properties['commands_callback_method'] + Internal async helper for fetch operation - @property - def sms_fallback_method(self): + Returns: + tuple: (payload, status_code, headers) """ - :returns: The HTTP method we use to call sms_fallback_url - :rtype: unicode - """ - return self._properties['sms_fallback_method'] - @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 - """ - return self._properties['sms_fallback_url'] + headers = values.of({}) - @property - def sms_method(self): + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> SimInstance: """ - :returns: The HTTP method we use to call sms_url - :rtype: unicode + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance """ - return self._properties['sms_method'] + payload, _, _ = await self._fetch_async() + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - @property - def sms_url(self): + async def fetch_with_http_info_async(self) -> ApiResponse: """ - :returns: The URL we call when the SIM-connected device sends an SMS message that is not a Command - :rtype: unicode + Asynchronous coroutine to fetch the SimInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._properties['sms_url'] + payload, status_code, headers = await self._fetch_async() + instance = SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 voice_fallback_method(self): + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: """ - :returns: The HTTP method we use to call voice_fallback_url - :rtype: unicode + Update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: The updated SimInstance """ - return self._properties['voice_fallback_method'] + payload, _, _ = self._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 SimInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + 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, + ) -> ApiResponse: + """ + Update the SimInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._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, + ) + instance = SimInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + "RatePlan": rate_plan, + "Status": status, + "CommandsCallbackMethod": commands_callback_method, + "CommandsCallbackUrl": commands_callback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "ResetStatus": reset_status, + "AccountSid": account_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: The updated SimInstance + """ + payload, _, _ = await self._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, + ) + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SimInstance and return response metadata + + :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: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._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, + ) + instance = SimInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def voice_fallback_url(self): + def data_sessions(self) -> DataSessionList: """ - :returns: The URL we call when an error occurs while retrieving or executing the TwiML requested from voice_url - :rtype: unicode + Access the data_sessions """ - return self._properties['voice_fallback_url'] + if self._data_sessions is None: + self._data_sessions = DataSessionList( + self._version, + self._solution["sid"], + ) + return self._data_sessions @property - def voice_method(self): + def usage_records(self) -> UsageRecordList: """ - :returns: The HTTP method we use to call voice_url - :rtype: unicode + Access the usage_records """ - return self._properties['voice_method'] + if self._usage_records is None: + self._usage_records = UsageRecordList( + self._version, + self._solution["sid"], + ) + return self._usage_records - @property - def voice_url(self): + def __repr__(self) -> str: """ - :returns: The URL we call when the SIM-connected device makes a voice call - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['voice_url'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def date_created(self): + +class SimPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SimInstance: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Build an instance of SimInstance + + :param payload: Payload response from the API """ - return self._properties['date_created'] - @property - def date_updated(self): + return SimInstance(self._version, payload) + + def __repr__(self) -> str: """ - :returns: The ISO 8601 date and time in GMT when the Sim resource was last updated - :rtype: datetime + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['date_updated'] + return "" - @property - def url(self): + +class SimList(ListResource): + + def __init__(self, version: Version): """ - :returns: The absolute URL of the resource - :rtype: unicode + Initialize the SimList + + :param version: Version that contains the resource + """ - return self._properties['url'] + super().__init__(version) - @property - def links(self): + self._uri = "/Sims" + + def stream( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SimInstance]: """ - :returns: The URLs of related subresources - :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['links'] + 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 ip_address(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: Deprecated - :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['ip_address'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) - def fetch(self): + def stream_with_http_info( + 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, + ) -> tuple: """ - Fetch the SimInstance + Streams SimInstance and returns headers from first page - :returns: The fetched SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimInstance + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - return self._proxy.fetch() + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) - 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): + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams SimInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances """ - Update the SimInstance + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) - :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 + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: The updated SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimInstance + 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]: """ - return self._proxy.update( - unique_name=unique_name, - callback_method=callback_method, - callback_url=callback_url, - friendly_name=friendly_name, + 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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists SimInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + iccid=iccid, rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists SimInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( 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, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimPage: + """ + Retrieve a single page of SimInstance records from the API. + Request is executed immediately + + :param status: Only return Sim resources with this status. + :param iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param e_id: Deprecated. + :param sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - def delete(self): + :returns: Page of SimInstance """ - Deletes 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: 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 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.delete() + 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 usage_records(self): + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimPage(self._version, response) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with SimPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SimPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with SimPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SimPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> SimPage: """ - Access the usage_records + Retrieve a specific page of SimInstance records from the API. + Request is executed immediately - :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimInstance """ - return self._proxy.usage_records + response = self._version.domain.twilio.request("GET", target_url) + return SimPage(self._version, response) - @property - def data_sessions(self): + async def get_page_async(self, target_url: str) -> SimPage: """ - Access the data_sessions + 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: twilio.rest.wireless.v1.sim.data_session.DataSessionList - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionList + :returns: Page of SimInstance """ - return self._proxy.data_sessions + response = await self._version.domain.twilio.request_async("GET", target_url) + return SimPage(self._version, response) + + def get(self, sid: str) -> SimContext: + """ + Constructs a SimContext + + :param sid: The SID or the `unique_name` of the Sim resource to update. + """ + return SimContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SimContext: + """ + Constructs a SimContext + + :param sid: The SID or the `unique_name` of the Sim resource to update. + """ + return SimContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly 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 cd36d09fc5..cb0c14dc69 100644 --- a/twilio/rest/wireless/v1/sim/data_session.py +++ b/twilio/rest/wireless/v1/sim/data_session.py @@ -1,348 +1,501 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class DataSessionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the DataSession resource. + :ivar sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) that the Data Session is for. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the DataSession resource. + :ivar radio_link: The generation of wireless technology that the device was using. + :ivar operator_mcc: The 'mobile country code' is the unique ID of the home country where the Data Session took place. See: [MCC/MNC lookup](http://mcc-mnc.com/). + :ivar operator_mnc: The 'mobile network code' is the unique ID specific to the mobile operator network where the Data Session took place. + :ivar operator_country: The three letter country code representing where the device's Data Session took place. This is determined by looking up the `operator_mcc`. + :ivar operator_name: The friendly name of the mobile operator network that the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource)-connected device is attached to. This is determined by looking up the `operator_mnc`. + :ivar cell_id: The unique ID of the cellular tower that the device was attached to at the moment when the Data Session was last updated. + :ivar cell_location_estimate: An object that describes the estimated location in latitude and longitude where the device's Data Session took place. The location is derived from the `cell_id` when the Data Session was last updated. See [Cell Location Estimate Object](https://www.twilio.com/docs/iot/wireless/api/datasession-resource#cell-location-estimate-object). + :ivar packets_uploaded: The number of packets uploaded by the device between the `start` time and when the Data Session was last updated. + :ivar packets_downloaded: The number of packets downloaded by the device between the `start` time and when the Data Session was last updated. + :ivar last_updated: The date that the resource was last updated, given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar start: The date that the Data Session started, given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar end: The date that the record ended, given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar imei: The 'international mobile equipment identity' is the unique ID of the device using the SIM to connect. An IMEI is a 15-digit string: 14 digits for the device identifier plus a check digit calculated using the Luhn formula. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.radio_link: Optional[str] = payload.get("radio_link") + self.operator_mcc: Optional[str] = payload.get("operator_mcc") + self.operator_mnc: Optional[str] = payload.get("operator_mnc") + self.operator_country: Optional[str] = payload.get("operator_country") + self.operator_name: Optional[str] = payload.get("operator_name") + self.cell_id: Optional[str] = payload.get("cell_id") + self.cell_location_estimate: Optional[Dict[str, object]] = payload.get( + "cell_location_estimate" + ) + self.packets_uploaded: Optional[int] = deserialize.integer( + payload.get("packets_uploaded") + ) + self.packets_downloaded: Optional[int] = deserialize.integer( + payload.get("packets_downloaded") + ) + self.last_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("last_updated") + ) + self.start: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start") + ) + self.end: Optional[datetime] = deserialize.iso8601_datetime(payload.get("end")) + self.imei: Optional[str] = payload.get("imei") + + self._solution = { + "sim_sid": sim_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DataSessionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DataSessionInstance: + """ + Build an instance of DataSessionInstance + + :param payload: Payload response from the API + """ + + return DataSessionInstance( + self._version, payload, sim_sid=self._solution["sim_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class DataSessionList(ListResource): - """ """ - def __init__(self, version, sim_sid): + def __init__(self, version: Version, sim_sid: str): """ 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 + :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: twilio.rest.wireless.v1.sim.data_session.DataSessionList - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionList """ - super(DataSessionList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'sim_sid': sim_sid, } - self._uri = '/Sims/{sim_sid}/DataSessions'.format(**self._solution) + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/DataSessions".format(**self._solution) - def stream(self, end=values.unset, start=values.unset, limit=None, - page_size=None): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DataSessionInstance]: """ Streams DataSessionInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param 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) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit 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.data_session.DataSessionInstance] """ limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - page = self.page(end=end, start=start, page_size=limits['page_size'], ) + return self._version.stream(page, limits["limit"]) - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, end=values.unset, start=values.unset, limit=None, - page_size=None): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[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. + Asynchronously streams DataSessionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :param 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) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit 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.data_session.DataSessionInstance] """ - return list(self.stream(end=end, start=start, limit=limit, page_size=page_size, )) + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - def page(self, end=values.unset, start=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Retrieve a single page of DataSessionInstance records from the API. - Request is executed immediately + Streams DataSessionInstance and returns headers from first page - :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 - :returns: Page of DataSessionInstance - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionPage - """ - data = values.of({ - 'End': serialize.iso8601_datetime(end), - 'Start': serialize.iso8601_datetime(start), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) - return DataSessionPage(self._version, response, self._solution) + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - def get_page(self, target_url): + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: """ - Retrieve a specific page of DataSessionInstance records from the API. - Request is executed immediately + Asynchronously streams DataSessionInstance and returns headers from first page - :param str target_url: API-generated URL for the requested results page - :returns: Page of DataSessionInstance - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionPage + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] ) - return DataSessionPage(self._version, response, self._solution) + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - def __repr__(self): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DataSessionInstance]: """ - Provide a friendly representation + 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: Machine friendly representation - :rtype: str - """ - return '' + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + :returns: list that will contain up to limit results + """ -class DataSessionPage(Page): - """ """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - def __init__(self, version, response, solution): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DataSessionInstance]: """ - Initialize the DataSessionPage + Asynchronously lists DataSessionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :param 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 + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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.wireless.v1.sim.data_session.DataSessionPage - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionPage + :returns: list that will contain up to limit results """ - super(DataSessionPage, self).__init__(version, response) - # Path Solution - self._solution = solution + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - def get_instance(self, payload): + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Build an instance of DataSessionInstance + Lists DataSessionInstance and returns headers from first page - :param dict payload: Payload response from the API - :returns: twilio.rest.wireless.v1.sim.data_session.DataSessionInstance - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionInstance - """ - return DataSessionInstance(self._version, payload, sim_sid=self._solution['sim_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) - def __repr__(self): + :returns: ApiResponse with list of instances, status code, and headers """ - Provide a friendly representation + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) - :returns: Machine friendly representation - :rtype: str + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - return '' + Asynchronously lists DataSessionInstance and returns headers from first page -class DataSessionInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, sim_sid): - """ - Initialize the DataSessionInstance - - :returns: twilio.rest.wireless.v1.sim.data_session.DataSessionInstance - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionInstance - """ - 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'), - } + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 = {'sim_sid': sim_sid, } - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: ApiResponse with list of instances, status code, and headers """ - return self._properties['sid'] + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) - @property - def sim_sid(self): - """ - :returns: The SID of the Sim resource that the Data Session is for - :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, + ) -> DataSessionPage: """ - return self._properties['sim_sid'] + Retrieve a single page of DataSessionInstance 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 radio_link(self): - """ - :returns: The generation of wireless technology that the device was using - :rtype: unicode + :returns: Page of DataSessionInstance """ - return self._properties['radio_link'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @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 - """ - return self._properties['operator_mcc'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @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'] + headers["Accept"] = "application/json" - @property - def operator_country(self): - """ - :returns: The three letter country code representing where the device's Data Session took place - :rtype: unicode - """ - return self._properties['operator_country'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DataSessionPage(self._version, response, solution=self._solution) - @property - def operator_name(self): + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DataSessionPage: """ - :returns: The friendly name of the mobile operator network that the SIM-connected device is attached to - :rtype: unicode - """ - return self._properties['operator_name'] + Asynchronously retrieve a single page of DataSessionInstance records from the API. + Request is executed immediately - @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'] + :param page_token: PageToken provided by the 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 cell_location_estimate(self): - """ - :returns: An object with the estimated location where the device's Data Session took place - :rtype: dict + :returns: Page of DataSessionInstance """ - return self._properties['cell_location_estimate'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def packets_uploaded(self): - """ - :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'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @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'] + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DataSessionPage(self._version, response, solution=self._solution) - @property - def last_updated(self): + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The date that the resource was last updated, given as GMT in ISO 8601 format - :rtype: datetime + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DataSessionPage, status code, and headers """ - return self._properties['last_updated'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def start(self): + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DataSessionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: """ - :returns: The date that the Data Session started, given as GMT in ISO 8601 format - :rtype: datetime + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DataSessionPage, status code, and headers """ - return self._properties['start'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def end(self): + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DataSessionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> DataSessionPage: """ - :returns: The date that the record ended, given as GMT in ISO 8601 format - :rtype: datetime + Retrieve a specific page of DataSessionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DataSessionInstance """ - return self._properties['end'] + response = self._version.domain.twilio.request("GET", target_url) + return DataSessionPage(self._version, response, solution=self._solution) - @property - def imei(self): + async def get_page_async(self, target_url: str) -> DataSessionPage: """ - :returns: The unique ID of the device using the SIM to connect - :rtype: unicode + Asynchronously retrieve a specific page of DataSessionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DataSessionInstance """ - return self._properties['imei'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return DataSessionPage(self._version, response, solution=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 42c38eddbc..5b1c6b2512 100644 --- a/twilio/rest/wireless/v1/sim/usage_record.py +++ b/twilio/rest/wireless/v1/sim/usage_record.py @@ -1,264 +1,577 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class UsageRecordInstance(InstanceResource): + + class Granularity(object): + HOURLY = "hourly" + DAILY = "daily" + ALL = "all" + + """ + :ivar sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) that this Usage Record is for. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resource. + :ivar period: The time period for which the usage is reported. Contains `start` and `end` datetime values given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar commands: An object that describes the SIM's usage of Commands during the specified period. See [Commands Usage Object](https://www.twilio.com/docs/iot/wireless/api/sim-usagerecord-resource#commands-usage-object). + :ivar data: An object that describes the SIM's data usage during the specified period. See [Data Usage Object](https://www.twilio.com/docs/iot/wireless/api/sim-usagerecord-resource#data-usage-object). + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): + super().__init__(version) + + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.period: Optional[Dict[str, object]] = payload.get("period") + self.commands: Optional[Dict[str, object]] = payload.get("commands") + self.data: Optional[Dict[str, object]] = payload.get("data") + + self._solution = { + "sim_sid": sim_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UsageRecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: + """ + Build an instance of UsageRecordInstance + + :param payload: Payload response from the API + """ + + return UsageRecordInstance( + self._version, payload, sim_sid=self._solution["sim_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class UsageRecordList(ListResource): - """ """ - def __init__(self, version, sim_sid): + def __init__(self, version: Version, sim_sid: str): """ Initialize the UsageRecordList - :param Version version: Version that contains the resource - :param sim_sid: The SID of the Sim resource that this Usage Record is for + :param version: Version that contains the resource + :param sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read the usage from. - :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList """ - super(UsageRecordList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'sim_sid': sim_sid, } - self._uri = '/Sims/{sim_sid}/UsageRecords'.format(**self._solution) + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/UsageRecords".format(**self._solution) - def stream(self, end=values.unset, start=values.unset, granularity=values.unset, - limit=None, page_size=None): + def stream( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UsageRecordInstance]: """ Streams UsageRecordInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param datetime end: 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) + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance] """ limits = self._version.read_limits(limit, page_size) + page = self.page( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) - page = self.page(end=end, start=start, granularity=granularity, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + return self._version.stream(page, limits["limit"]) - def list(self, end=values.unset, start=values.unset, granularity=values.unset, - limit=None, page_size=None): + async def stream_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UsageRecordInstance]: """ - Lists UsageRecordInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronously streams UsageRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :param datetime end: 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) + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance] - """ - return list(self.stream( - end=end, - start=start, - granularity=granularity, - limit=limit, - page_size=page_size, - )) - - def page(self, end=values.unset, start=values.unset, granularity=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): """ - Retrieve a single page of UsageRecordInstance records from the API. - Request is executed immediately + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) - :param datetime end: 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 + return self._version.stream_async(page, limits["limit"]) - :returns: Page of UsageRecordInstance - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordPage + def stream_with_http_info( + 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, + ) -> tuple: """ - data = values.of({ - 'End': serialize.iso8601_datetime(end), - 'Start': serialize.iso8601_datetime(start), - 'Granularity': granularity, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Streams UsageRecordInstance and returns headers from first page - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return UsageRecordPage(self._version, response, self._solution) + :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) - def get_page(self, target_url): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Retrieve a specific page of UsageRecordInstance records from the API. - Request is executed immediately + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) - :param str target_url: API-generated URL for the requested results page + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - :returns: Page of UsageRecordInstance - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordPage + async def stream_with_http_info_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, + ) -> tuple: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronously streams UsageRecordInstance and returns headers from first page + - return UsageRecordPage(self._version, response, self._solution) + :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) - def __repr__(self): + :returns: tuple of (generator, status_code, headers) where generator yields instances """ - Provide a friendly representation + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) - :returns: Machine friendly representation - :rtype: str + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + 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]: """ - return '' + Lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + ) -class UsageRecordPage(Page): - """ """ + async def list_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsageRecordInstance]: + """ + Asynchronously lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - def __init__(self, version, response, solution): + :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 list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists UsageRecordInstance and returns headers from first 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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists UsageRecordInstance and returns headers from first 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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + 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: """ - Initialize the UsageRecordPage + Retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately - :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 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.UsageRecordPage - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordPage + :returns: Page of UsageRecordInstance """ - super(UsageRecordPage, self).__init__(version, response) + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - # Path Solution - self._solution = solution + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def get_instance(self, payload): - """ - Build an instance of UsageRecordInstance + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response, solution=self._solution) + + async def page_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsageRecordPage: + """ + Asynchronously retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately - :param 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response, solution=self._solution) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with UsageRecordPage, status code, and headers + """ + 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, sim_sid): - """ - Initialize the UsageRecordInstance + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UsageRecordPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with UsageRecordPage, status code, and headers + """ + 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) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # 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["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'sim_sid': sim_sid, } + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UsageRecordPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - @property - def sim_sid(self): + def get_page(self, target_url: str) -> UsageRecordPage: """ - :returns: The SID of the Sim resource that this Usage Record is for - :rtype: unicode - """ - return self._properties['sim_sid'] + Retrieve a specific page of UsageRecordInstance 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 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, solution=self._solution) - @property - def commands(self): - """ - :returns: An object that describes the SIM's usage of Commands during the specified period - :rtype: dict + async def get_page_async(self, target_url: str) -> UsageRecordPage: """ - return self._properties['commands'] + Asynchronously retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately - @property - def data(self): - """ - :returns: An object that describes the SIM's data usage during the specified period - :rtype: dict + :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, solution=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 aea8725906..034ab18ab2 100644 --- a/twilio/rest/wireless/v1/usage_record.py +++ b/twilio/rest/wireless/v1/usage_record.py @@ -1,253 +1,564 @@ -# 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page +class UsageRecordInstance(InstanceResource): + + class Granularity(object): + HOURLY = "hourly" + DAILY = "daily" + ALL = "all" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AccountUsageRecord resource. + :ivar period: The time period for which usage is reported. Contains `start` and `end` properties that describe the period using GMT date-time values specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar commands: An object that describes the aggregated Commands usage for all SIMs during the specified period. See [Commands Usage Object](https://www.twilio.com/docs/iot/wireless/api/account-usagerecord-resource#commands-usage-object). + :ivar data: An object that describes the aggregated Data usage for all SIMs over the period. See [Data Usage Object](https://www.twilio.com/docs/iot/wireless/api/account-usagerecord-resource#data-usage-object). + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.period: Optional[Dict[str, object]] = payload.get("period") + self.commands: Optional[Dict[str, object]] = payload.get("commands") + self.data: Optional[Dict[str, object]] = payload.get("data") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class UsageRecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: + """ + Build an instance of UsageRecordInstance + + :param payload: Payload response from the API + """ + + return UsageRecordInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + class UsageRecordList(ListResource): - """ """ - def __init__(self, version): + def __init__(self, version: Version): """ Initialize the UsageRecordList - :param Version version: Version that contains the resource + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/UsageRecords" + + def stream( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UsageRecordInstance]: + """ + Streams UsageRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - :returns: twilio.rest.wireless.v1.usage_record.UsageRecordList - :rtype: twilio.rest.wireless.v1.usage_record.UsageRecordList + :returns: Generator that will yield up to limit results """ - super(UsageRecordList, self).__init__(version) + limits = self._version.read_limits(limit, page_size) + page = self.page( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) - # Path Solution - self._solution = {} - self._uri = '/UsageRecords'.format(**self._solution) + return self._version.stream(page, limits["limit"]) - def stream(self, end=values.unset, start=values.unset, granularity=values.unset, - limit=None, page_size=None): + async def stream_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UsageRecordInstance]: """ - Streams UsageRecordInstance records from the API as a generator stream. + Asynchronously streams UsageRecordInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. - :param datetime end: Only include usage that has occurred on or before this date - :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) + :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 - :rtype: list[twilio.rest.wireless.v1.usage_record.UsageRecordInstance] """ limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + 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, + ) -> tuple: + """ + Streams UsageRecordInstance and returns headers from first 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_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, + ) -> tuple: + """ + Asynchronously streams UsageRecordInstance and returns headers from first page - page = self.page(end=end, start=start, granularity=granularity, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) - def list(self, end=values.unset, start=values.unset, granularity=values.unset, - limit=None, page_size=None): + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsageRecordInstance]: """ Lists UsageRecordInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param datetime end: Only include usage that has occurred on or before this date - :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 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 + """ - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.usage_record.UsageRecordInstance] + return list( + self.stream( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsageRecordInstance]: + """ + Asynchronously lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return list(self.stream( + + return [ + record + async for record in await self.stream_async( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + 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, + ) -> ApiResponse: + """ + Lists UsageRecordInstance and returns headers from first 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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( end=end, start=start, granularity=granularity, limit=limit, page_size=page_size, - )) + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously lists UsageRecordInstance and returns headers from first page - def page(self, end=values.unset, start=values.unset, granularity=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsageRecordPage: """ Retrieve a single page of UsageRecordInstance records from the API. Request is executed immediately - :param 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 + :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 - :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, - }) + 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, ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - return UsageRecordPage(self._version, response, self._solution) + headers["Accept"] = "application/json" - def get_page(self, target_url): + 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: """ - Retrieve a specific page of UsageRecordInstance records from the API. + Asynchronously retrieve a single page of UsageRecordInstance records from the API. Request is executed immediately - :param str target_url: API-generated URL for the requested results page + :param end: Only include usage that 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 - :rtype: twilio.rest.wireless.v1.usage_record.UsageRecordPage """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } ) - return UsageRecordPage(self._version, response, self._solution) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def __repr__(self): - """ - Provide a friendly representation + headers["Accept"] = "application/json" - :returns: Machine friendly representation - :rtype: str + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response) + + def page_with_http_info( + 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, + ) -> ApiResponse: """ - return '' + Retrieve a single page with response metadata -class UsageRecordPage(Page): - """ """ + :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 __init__(self, version, response, solution): + :returns: ApiResponse with UsageRecordPage, status code, and headers """ - Initialize the UsageRecordPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + 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.usage_record.UsageRecordPage - :rtype: twilio.rest.wireless.v1.usage_record.UsageRecordPage - """ - super(UsageRecordPage, self).__init__(version, response) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Path Solution - self._solution = solution + headers["Accept"] = "application/json" - def get_instance(self, payload): + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UsageRecordPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: """ - Build an instance of UsageRecordInstance + Asynchronously retrieve a single page with response metadata - :param dict payload: Payload response from the API - - :returns: twilio.rest.wireless.v1.usage_record.UsageRecordInstance - :rtype: twilio.rest.wireless.v1.usage_record.UsageRecordInstance - """ - return UsageRecordInstance(self._version, payload, ) - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: ApiResponse with UsageRecordPage, status code, and headers """ - return '' + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class UsageRecordInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - class Granularity(object): - HOURLY = "hourly" - DAILY = "daily" - ALL = "all" - - def __init__(self, version, payload): - """ - Initialize the UsageRecordInstance + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UsageRecordPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) - :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): - """ - :returns: The time period for which usage is reported - :rtype: dict + async def get_page_async(self, target_url: str) -> UsageRecordPage: """ - 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 24ed222766..384c492778 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,30 @@ 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_configuration_id=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 @@ -52,31 +67,45 @@ def dial(self, number=None, action=None, method=None, timeout=None, :param record: Record the call :param trim: Trim the recording :param recording_status_callback: Recording status callback URL + :param recording_configuration_id: Configuration for the recording :param recording_status_callback_method: Recording status callback URL method :param recording_status_callback_event: Recording status callback events :param answer_on_bridge: Preserve the ringing behavior of the inbound call until the Dialed call picks up :param ring_tone: Ringtone allows you to override the ringback tone that Twilio will play back to the caller while executing the Dial + :param recording_track: To indicate which audio track should be recorded + :param sequential: Used to determine if child TwiML nouns should be dialed in order, one after the other (sequential) or dial all at once (parallel). Default is false, parallel + :param refer_url: Webhook that will receive future SIP REFER requests + :param refer_method: The HTTP method to use for the refer Webhook + :param events: Subscription to events :param kwargs: additional attributes :returns: 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_configuration_id=recording_configuration_id, + 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 +117,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 +142,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, **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 @@ -139,30 +197,34 @@ def gather(self, input=None, action=None, method=None, timeout=None, :param debug: Allow debug for gather :param action_on_empty_result: Force webhook to the action URL event if there is no input :param speech_model: Specify the model that is best suited for your use case + :param enhanced: Use enhanced speech model :param kwargs: additional attributes :returns: element """ - return self.nest(Gather( - input=input, - action=action, - method=method, - timeout=timeout, - speech_timeout=speech_timeout, - max_speech_time=max_speech_time, - profanity_filter=profanity_filter, - finish_on_key=finish_on_key, - num_digits=num_digits, - partial_result_callback=partial_result_callback, - partial_result_callback_method=partial_result_callback_method, - language=language, - hints=hints, - barge_in=barge_in, - debug=debug, - action_on_empty_result=action_on_empty_result, - speech_model=speech_model, - **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): """ @@ -208,8 +270,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 @@ -222,21 +291,34 @@ 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, + recording_configuration_id=None, + **kwargs + ): """ Create a element @@ -252,25 +334,29 @@ def record(self, action=None, method=None, timeout=None, finish_on_key=None, :param recording_status_callback_event: Recording status callback events :param transcribe: Transcribe the recording :param transcribe_callback: Transcribe callback URL + :param recording_configuration_id: Configuration for the recording :param kwargs: additional attributes :returns: element """ - return self.nest(Record( - action=action, - method=method, - timeout=timeout, - finish_on_key=finish_on_key, - max_length=max_length, - play_beep=play_beep, - trim=trim, - recording_status_callback=recording_status_callback, - recording_status_callback_method=recording_status_callback_method, - 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, + recording_configuration_id=recording_configuration_id, + **kwargs + ) + ) def redirect(self, url, method=None, **kwargs): """ @@ -302,15 +388,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 @@ -324,22 +420,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 @@ -365,30 +479,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 @@ -396,17 +519,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): """ @@ -444,11 +571,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): """ @@ -461,37 +588,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 @@ -499,32 +622,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): """ @@ -540,19 +765,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): """ @@ -568,14 +821,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 @@ -583,32 +844,168 @@ 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 + ) + ) + + def recording( + self, + recording_status_callback=None, + recording_status_callback_method=None, + recording_status_callback_event=None, + trim=None, + track=None, + channels=None, + recording_configuration_id=None, + **kwargs + ): + """ + Create a element + + :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 trim: Trim the recording + :param track: To indicate which audio track should be recorded + :param channels: The recording channels for the final recording + :param recording_configuration_id: Configuration for the recording + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Recording( + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + trim=trim, + track=track, + channels=channels, + recording_configuration_id=recording_configuration_id, + **kwargs + ) + ) + + +class Recording(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Recording, self).__init__(**kwargs) + self.name = "Recording" 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): """ @@ -617,12 +1014,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): """ @@ -650,29 +1049,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 @@ -688,33 +1087,7 @@ 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): - """ - 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.break_(strength=strength, time=time, **kwargs) - - def emphasis(self, words, 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, level=level, **kwargs)) - - @deprecated_method('emphasis') - def ssml_emphasis(self, words, level=None, **kwargs): + def emphasis(self, words=None, level=None, **kwargs): """ Create a element @@ -724,22 +1097,9 @@ def ssml_emphasis(self, words, level=None, **kwargs): :returns: element """ - return self.emphasis(words, level=level, **kwargs) - - def lang(self, words, 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, xml_lang=xml_lang, **kwargs)) + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) - @deprecated_method('lang') - def ssml_lang(self, words, xml_lang=None, **kwargs): + def lang(self, words=None, xml_lang=None, **kwargs): """ Create a element @@ -749,21 +1109,9 @@ def ssml_lang(self, words, xml_lang=None, **kwargs): :returns: element """ - return self.lang(words, xml_lang=xml_lang, **kwargs) - - def p(self, words, **kwargs): - """ - Create a

    element - - :param words: Words to speak - :param kwargs: additional attributes + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) - :returns:

    element - """ - return self.nest(SsmlP(words, **kwargs)) - - @deprecated_method('p') - def ssml_p(self, words, **kwargs): + def p(self, words=None, **kwargs): """ Create a

    element @@ -772,7 +1120,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): """ @@ -787,21 +1135,7 @@ 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): - """ - 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.phoneme(words, alphabet=alphabet, ph=ph, **kwargs) - - def prosody(self, words, volume=None, rate=None, pitch=None, **kwargs): + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): """ Create a element @@ -813,222 +1147,827 @@ def prosody(self, words, volume=None, rate=None, pitch=None, **kwargs): :returns: element """ - return self.nest(SsmlProsody(words, volume=volume, rate=rate, pitch=pitch, **kwargs)) + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) - @deprecated_method('prosody') - def ssml_prosody(self, words, volume=None, rate=None, pitch=None, **kwargs): + def s(self, words=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 kwargs: additional attributes - :returns: element + :returns: element """ - return self.prosody(words, volume=volume, rate=rate, pitch=pitch, **kwargs) + return self.nest(SsmlS(words=words, **kwargs)) - def s(self, words, **kwargs): + def say_as(self, words, interpret_as=None, format=None, **kwargs): """ - Create a element + Create a element - :param words: Words to speak + :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.nest(SsmlS(words, **kwargs)) + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) - @deprecated_method('s') - def ssml_s(self, words, **kwargs): + def sub(self, words, alias=None, **kwargs): """ - Create a element + Create a element - :param words: Words to speak + :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 + :returns: element """ - return self.s(words, **kwargs) + return self.nest(SsmlSub(words, alias=alias, **kwargs)) - def say_as(self, words, interpret_as=None, role=None, **kwargs): + def w(self, words=None, role=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 role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning :param kwargs: additional attributes - :returns: element + :returns: element """ - return self.nest(SsmlSayAs(words, interpret_as=interpret_as, role=role, **kwargs)) + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlW(TwiML): + """Improving Pronunciation by Specifying Parts of Speech in """ - @deprecated_method('say_as') - def ssml_say_as(self, words, interpret_as=None, role=None, **kwargs): + 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 + 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 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.say_as(words, interpret_as=interpret_as, role=role, **kwargs) + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) - def sub(self, words, alias=None, **kwargs): + def emphasis(self, words=None, level=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 words: Words to emphasize + :param level: Specify the degree of emphasis :param kwargs: additional attributes - :returns: element + :returns: element """ - return self.nest(SsmlSub(words, alias=alias, **kwargs)) + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) - @deprecated_method('sub') - def ssml_sub(self, words, alias=None, **kwargs): + def phoneme(self, words, alphabet=None, ph=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 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.sub(words, alias=alias, **kwargs) + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) - def w(self, words, 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 speak - :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :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(SsmlW(words, role=role, **kwargs)) + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) - @deprecated_method('w') - def ssml_w(self, words, role=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 role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :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.w(words, role=role, **kwargs) + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + def sub(self, words, alias=None, **kwargs): + """ + Create a element -class SsmlW(TwiML): - """ Improving Pronunciation by Specifying Parts of Speech in """ + :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 - def __init__(self, words, **kwargs): - super(SsmlW, self).__init__(**kwargs) - self.name = 'w' - self.value = words + :returns: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) class SsmlSub(TwiML): - """ Pronouncing Acronyms and Abbreviations in """ + """Pronouncing Acronyms and Abbreviations in """ def __init__(self, words, **kwargs): super(SsmlSub, self).__init__(**kwargs) - self.name = 'sub' + self.name = "sub" self.value = words class SsmlSayAs(TwiML): - """ Controlling How Special Types of Words Are Spoken in """ + """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.name = "say-as" self.value = words class SsmlProsody(TwiML): - """ Controling Volume, Speaking Rate, and Pitch in """ + """Controling Volume, Speaking Rate, and Pitch in """ - def __init__(self, words, **kwargs): + def __init__(self, words=None, **kwargs): super(SsmlProsody, self).__init__(**kwargs) - self.name = 'prosody' - self.value = words + self.name = "prosody" + if words: + self.value = words + def break_(self, strength=None, time=None, **kwargs): + """ + Create a element -class SsmlPhoneme(TwiML): - """ Using Phonetic Pronunciation in """ + :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 - def __init__(self, words, **kwargs): - super(SsmlPhoneme, self).__init__(**kwargs) - self.name = 'phoneme' - self.value = words + :returns: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element -class SsmlP(TwiML): - """ Adding a Pause Between Paragraphs in """ + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes - def __init__(self, words, **kwargs): - super(SsmlP, self).__init__(**kwargs) - self.name = 'p' - self.value = words + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element -class SsmlLang(TwiML): - """ Specifying Another Language for Specific Words in """ + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes - def __init__(self, words, **kwargs): - super(SsmlLang, self).__init__(**kwargs) - self.name = 'lang' - self.value = words + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + def p(self, words=None, **kwargs): + """ + Create a

    element -class SsmlEmphasis(TwiML): - """ Emphasizing Words in """ + :param words: Words to speak + :param kwargs: additional attributes - def __init__(self, words, **kwargs): - super(SsmlEmphasis, self).__init__(**kwargs) - self.name = 'emphasis' - self.value = words + :returns:

    element + """ + return self.nest(SsmlP(words=words, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def s(self, words=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlS(words=words, **kwargs)) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlS(TwiML): + """Adding A Pause Between Sentences in """ + + def __init__(self, words=None, **kwargs): + super(SsmlS, self).__init__(**kwargs) + self.name = "s" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlPhoneme(TwiML): + """Using Phonetic Pronunciation in """ + + def __init__(self, words, **kwargs): + super(SsmlPhoneme, self).__init__(**kwargs) + self.name = "phoneme" + self.value = words + + +class SsmlLang(TwiML): + """Specifying Another Language for Specific Words in """ + + def __init__(self, words=None, **kwargs): + super(SsmlLang, self).__init__(**kwargs) + self.name = "lang" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def p(self, words=None, **kwargs): + """ + Create a

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

    element + """ + return self.nest(SsmlP(words=words, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def s(self, words=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlS(words=words, **kwargs)) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlP(TwiML): + """Adding a Pause Between Paragraphs in """ + + def __init__(self, words=None, **kwargs): + super(SsmlP, self).__init__(**kwargs) + self.name = "p" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def s(self, words=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlS(words=words, **kwargs)) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlEmphasis(TwiML): + """Emphasizing Words in """ + + def __init__(self, words=None, **kwargs): + super(SsmlEmphasis, self).__init__(**kwargs) + self.name = "emphasis" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) class SsmlBreak(TwiML): - """ Adding a Pause in """ + """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 @@ -1036,17 +1975,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): """ @@ -1062,70 +2005,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): """ @@ -1134,12 +2101,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): """ @@ -1167,11 +2136,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 @@ -1190,34 +2159,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 @@ -1231,25 +2207,44 @@ 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, + recording_configuration_id=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 @@ -1262,6 +2257,7 @@ def conference(self, name, muted=None, beep=None, :param wait_method: Wait URL method :param max_participants: Maximum number of participants :param record: Record the conference + :param recording_configuration_id: Configuration for the recording :param region: Conference region :param coach: Call coach :param trim: Trim the conference recording @@ -1272,36 +2268,59 @@ 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, + recording_configuration_id=recording_configuration_id, + 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 @@ -1313,24 +2332,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 @@ -1343,14 +2385,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): """ @@ -1363,9 +2407,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=None, + 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 @@ -1377,65 +2437,291 @@ 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=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 + ) + ) + + def whats_app( + self, + phone_number, + url=None, + method=None, + status_callback_event=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a element + + :param phone_number: WhatsApp Phone Number to dial + :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 kwargs: additional attributes + + :returns: element + """ + return self.nest( + WhatsApp( + phone_number, + url=url, + method=method, + status_callback_event=status_callback_event, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + +class WhatsApp(TwiML): + """ TwiML Noun""" + + def __init__(self, phone_number, **kwargs): + super(WhatsApp, self).__init__(**kwargs) + self.name = "WhatsApp" + self.value = phone_number + + +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): + def __init__(self, sip_url=None, **kwargs): super(Sip, self).__init__(**kwargs) - self.name = 'Sip' - self.value = sip_url + self.name = "Sip" + if sip_url: + self.value = sip_url + + def uri( + self, + sip_url=None, + priority=None, + weight=None, + username=None, + password=None, + **kwargs + ): + """ + Create a element + + :param sip_url: The SIP URI + :param priority: The priority of this SIP URI + :param weight: The weight of this SIP URI + :param username: The username for authentication + :param password: The password for authentication + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SipUri( + sip_url=sip_url, + priority=priority, + weight=weight, + username=username, + password=password, + **kwargs + ) + ) + + def headers(self, **kwargs): + """ + Create a element + + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Headers(**kwargs)) + + +class Headers(TwiML): + """The SIP headers to include in the request""" + + def __init__(self, **kwargs): + super(Headers, self).__init__(**kwargs) + self.name = "Headers" + + def header(self, name=None, value=None, **kwargs): + """ + Create a

    element + + :param name: The name of the custom header + :param value: The value of the custom header + :param kwargs: additional attributes + + :returns:
    element + """ + return self.nest(Header(name=name, value=value, **kwargs)) + + +class Header(TwiML): + """A custom SIP header to include in the request""" + + def __init__(self, **kwargs): + super(Header, self).__init__(**kwargs) + self.name = "Header" + + +class SipUri(TwiML): + """The SIP URI to dial. Multiple Uri elements can be provided, in which + case they will be attempted in priority order. URIs with the same priority + will be selected proportionally based on its weight.""" + + def __init__(self, sip_url=None, **kwargs): + super(SipUri, self).__init__(**kwargs) + self.name = "Uri" + if sip_url: + 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 @@ -1464,20 +2750,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): """ @@ -1489,7 +2775,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): """ @@ -1502,8 +2790,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 @@ -1511,26 +2807,510 @@ 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, + backgroundNoiseReduction=None, + speechTimeout=None, + deepgramSmartFormat=None, + ignoreBackchannel=None, + events=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 backgroundNoiseReduction: This parameters enables background noise filtering on the audio stream before it reaches the STT engine, improving transcription accuracy in noisy environments + :param speechTimeout: Set the duration of silence that indicates the end of speech + :param deepgramSmartFormat: This parameter enables Deepgram's smart formatting feature, which automatically applies punctuation, capitalization, and formatting (e.g. numbers, dates, currency) to transcripts + :param ignoreBackchannel: This parameter brief caller acknowledgments (e.g. "yeah", "uh-huh") are ignored and will not interrupt the agent while it is speaking. + :param events: This parameter allows you to enable event subscriptions + :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, + backgroundNoiseReduction=backgroundNoiseReduction, + speechTimeout=speechTimeout, + deepgramSmartFormat=deepgramSmartFormat, + ignoreBackchannel=ignoreBackchannel, + events=events, + **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 + ) + ) + + def ai_session(self, ai_connector=None, ai_session_configuration=None, **kwargs): + """ + Create a element + + :param ai_connector: The unique name or installed add-on sid that identifies the installed addon resource for the AI Connector + :param ai_session_configuration: The unique name or id of the AiSession Configuration resource. + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + AiSession( + ai_connector=ai_connector, + ai_session_configuration=ai_session_configuration, + **kwargs + ) + ) + + def conversation_relay_session( + self, connector=None, session_configuration=None, **kwargs + ): + """ + Create a element + + :param connector: The unique name or installed add-on sid that identifies the installed addon resource for the ConversationRelaySession Connector + :param session_configuration: The unique name or id of the ConversationRelaySession Configuration resource. + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + ConversationRelaySession( + connector=connector, + session_configuration=session_configuration, + **kwargs + ) + ) + + +class ConversationRelaySession(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(ConversationRelaySession, self).__init__(**kwargs) + self.name = "ConversationRelaySession" + + +class AiSession(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(AiSession, self).__init__(**kwargs) + self.name = "AiSession" + + +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